2016 360笔试题------找镇长

public class Main {

public static void main(String[] args) {

int count, n ,m;
int relation [][];
int x, y;
int result;

Scanner s = new Scanner(System.in);
int number = s.nextInt();  //保存数据的组数
while(number-- > 0){

count = 0;  //记录是不是一组数据,除掉开头的第一行
n = s.nextInt();
m = s.nextInt();
relation = new int [n][n];    //创建一个二维的关系数组,排序从0开始的
for(int i=0; i<n; i++)              //初始化数组
relation[i][i] = 1;      //自己认识自己

while(count < m){//这是一组数据
count++;
x = s.nextInt();
y = s.nextInt();
relation[x-1][y-1] = 1;     //此关系成立 ----->表示x认识y
}
result = judge(relation);          //找出镇长的合适人选
if(result == 0)
System.out.println(0);
else{
System.out.println(1);
System.out.print(result);
}
System.out.println();
}
s.close();
}


private static int judge(int[][] relation) {
   
for(int i=0; i<relation.length; i++){
boolean flag = true;   //标记是否所有人都认识他
for(int j=0; j<relation.length; j++){
if(relation[j][i] == 1){     //j认识i

}else{
flag = false;
break;
}
}
if(flag){ //所有人都认识i,那么要判断是否i认识除自己外的其他人
for(int k=0; k<relation.length; k++)
if(i!=k && relation[i][k]==1){  //认识了其他人
flag = false;
break;
}
}
if(flag){//满足条件,而且满足这样条件的只有一个人
return i+1;
}

}
return 0;
}

猜你喜欢

转载自blog.csdn.net/u012571415/article/details/47788361