ACM详解(10)——辽宁省赛(上)
第一题:Dinner
Timelimit: 1s Memorylimit:32M
Description
Little A is one member of ACM team. He had just won the gold in World Final. To celebrate, he decided to invite all to have one meal. As bowl, knife and other tableware is not enough in the kitchen, Little A goes to take backup tableware in warehouse. There are many boxes in warehouse, one box contains only one thing, and each box is marked by the name of things inside it. For example, if "basketball" is written on the box, which means the box contains only basketball. With these marks, Little A wants to find out the tableware easily. So, the problem for you is to help him, find out all the tableware from all boxes in the warehouse.
Input
There are many test cases. Each case contains one line, and one integer N at the first, N indicates that there are N boxes in the warehouse. Then N strings follow, each string is one name written on the box.
Output
For each test of the input, output all the name of tableware.对于每组测试数据,输出餐具的名字。
Sample Input
3 basketball fork chopsticks
2 bowl letter
Sample Output
fork chopsticks
bowl
HINT:
The tableware only contains: bowl, knife, fork and chopsticks.
解题思路
从输入中得到物品集合,然后判断是不是餐具即可。参考代码如下:
/*
* Dinner
*/
public static void test7(Scanner scanner){
String[] s=new String[]{"bowl","knife","fork","chopsticks"};
int n=scanner.nextInt();
int index=0;
for(int i=0;i<n;i++){
String temp = scanner.next();
for(String temp2:s){
if(temp.equals(temp2)){
if(index!=0)
System.out.print(" ");
System.out.print(temp);
index++;
break;
}
}
}
System.out.println();
}
第二题:You are my brother
Timelimit: 1s Memorylimit:32M
Description
最近Little A认识了一个新的朋友Little B,在他们聊天的时候他们竟然发现500年前他们是一家人,现在Little A想知道Little是他的长辈,晚辈,还是兄弟。
Input
There are several test cases.
每组测试数据首先输入一个整数N(N<=1000),接着N行,每行两个整数a,b表示a的父亲是b(1<=a,b<=2000)。Little的编号为1,Little的编号为2。每个人只能有一个父亲。
Proceed to the end of file.
Output
对于每组测试数据,如果Little B是Little A的晚辈,则输出”You are my younger”,如果Little B是Little A的长辈,则输出”You are my elder”,如果是同辈则输出”You are my brother”。
Sample Input
5
1 3
2 4
3 5
4 6
5 6
6
1 3
2 4
3 5
4 6
5 7
6 7
Sample Output
You are my elder
You are my brother
解题思路
500年前是一家,意味着他们有共同的祖先,所以只要找到他们共同的祖先,然后算出来他们分别属于第几代子孙,就可以知道他们之间的关系了。因为每个人只能有一个父亲,所以可以使用数组下标与元素值来表示孩子与父亲的关系,例如a[4]=8,表示第5个人的父亲是第8个人。
参考代码如下:
/*
* you are my brother
*/
public static void test6(Scanner scanner){
int n=scanner.nextInt();
int[] data = new int[n+1];
for(int i=0;i<n;i++){
int a=scanner.nextInt();
int b=scanner.nextInt();
data[a-1]=b;
}
int d1=0;
int d2=0;
int temp=1;
while(data[temp-1]!=0){
d1++;
temp = data[temp-1];
}
temp=2;
while(data[temp-1]!=0){
d2++;
temp = data[temp-1];
}
if(d1>d2){
System.out.println("You are my elder");
补充:软件开发 , Java ,