Sicily 2012. King 解题报告
题目:
Constraints
Time Limit: 1 secs, Memory Limit: 256 MB , Special Judge
Description
There are n children in a country marked by integers from 1 to n.
They often fight with each other. For each pair of child A and child B, either A beats B or B beats A. It is not possible that both A beats B and B beats A. Of course, one never fight with himself.
Child A is not afraid of child B if A can beat B.
Child A is not afraid of child B if A can beat C and C can beat B either. Because A can say "I will call C to beat you" to B.
A child is called a king of children if he is not afraid of any other child.
Give you the beating relations.Find a king.
Input
The first line contains a integer n which is between 1 and 1000. The following n lines contains n characters respectively. Character is either '0' or '1'. The Bth character of (A+1)th line will be '1' if and only if A can beat B. Input is terminated by EOF.
Output
A number representing a king of children on a line. If such a king does not exist, output -1. If there are multiple kings, any one is accepted.
Sample Input
2 01 00
Sample Output
1
思路:
题目比较简单,从n个孩子中只要找出一个不怕任何一个孩子的即可。
对于第i个孩子,如果他与第j个孩子的关系为1说明他能打过j当然不怕他,如果关系为0则从第i个孩子能打过的人中找出一个能打过j的人。
1 #include<iostream> 2 using namespace std; 3 4 bool isTheKing(int i,string *beatRelations,int n); 5 bool isNotAfraidOf(string *beatRelations,int i,int j,int n); 6 7 int main(){ 8 int n; 9 while(cin>>n){ //C++用循环输入可以实现题目的eof结束输入 10 string beatRelations[n]; 11 for(int i=0;i<n;i++){ 12 cin>>beatRelations[i]; 13 } 14 for(int i=0;i<n;i++){ 15 if(i==n-1){ 16 if(isTheKing(i,beatRelations,n)){ 17 cout<<n<<endl; 18 }else 19 cout<<-1<<endl; //最后一个孩子仍然不是king时要输出-1 20 }else{ 21 if(isTheKing(i,beatRelations,n)){ 22 cout<<i+1<<endl; 23 break; 24 } 25 } 26 } 27 } 28 return 0; 29 } 30 31 bool isTheKing(int i,string *beatRelations,int n){ 32 for(int j=0;j<n;j++){ //遇到他害怕的孩子说明不是king即返回false 33 if(beatRelations[i][j]=='0'&&i!=j){ 34 if(!isNotAfraidOf(beatRelations,i,j,n)) //beatRelations[i][j]=='0'要进行进一步的判断 35 return false; 36 } 37 } 38 return true; 39 } 40 bool isNotAfraidOf(string *beatRelations,int i,int j,int n){ //从他能打过的孩子中找能打过第j个孩子的人 41 for(int k=0;k<n;k++){ 42 if(beatRelations[i][k]=='1'&&beatRelations[k][j]=='1') 43 return true; 44 } 45 return false; 46 }