这是一个笔试题,当时写到一半没时间了,好可惜啊,,,,,,,要是能再多给我5分钟就好了。。。。。
公司有n个员工,编号为0~n-1,公司有m个团体,每个员工可以参加多个团体,也可以不·参加。如果一个员工获得一个通知,他可以通知所在团体中的其他人,得知消息的员工又可以去其他所在团体进行通知。现编号为0的员工获得一个通知,求最终获得通知的人数。
输入:第一行分别输入员工数和团体数;接下来m行第一个数代表团体人数,后面数字代表团体的员工编号。
输出:获得通知的人数。
输入示例:
50 5
2 1 2
5 10 11 12 13 14
2 0 1
2 49 2
4 6 7 8 2
输出示例:7
获得通知的员工:0,1,2,6,7,8,49共7人
思路:很显然可以用递归来实现,用布尔数组noti[]保存每个团体是否通知过.
public class Main {
public static Set<Integer> know=new HashSet<Integer>();
public static int m,n;
public static boolean noti[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m=sc.nextInt();
boolean hasZ=false;
noti=new boolean[m];
Arrays.fill(noti, false);
int zx=0,zy=0;
List<List<Integer>> team=new ArrayList<List<Integer>>();
for(int i=0;i<m;i++){
List<Integer> teamM=new ArrayList<Integer>();
int teamNum=sc.nextInt();
for (int j = 0; j < teamNum; j++) {
teamM.add(sc.nextInt());
if (teamM.get(j)==0) {
hasZ=true;
zx=i;zy=j;
}
}
team.add(teamM);
}
notice(team,zx,zy);
System.out.println(know.size());
}
public static void notice(List<List<Integer>> team,int teamNo,int y) {
if (noti[teamNo]) {
return;
}
List<Integer> teamIn=team.get(teamNo);
for(int i=0;i<teamIn.size();i++) {
if(!know.contains(teamIn.get(i))) {
know.add(teamIn.get(i));
for(int mi=0;mi<m;mi++){
for(int ji=0;ji<team.get(mi).size();ji++){
if(teamIn.get(i)==team.get(mi).get(ji)){
notice(team, mi,ji);
noti[mi]=true;
}
}
}
}
}
}
}
输出测试:
蓝瘦,香菇,当时没时间写了,就这样丢了20分.