幼儿园分班
说明:不喜欢的人不能分在一起,查询是否有解决方案
思路:无法分班的情况是,当一个班级同时包含两个不喜欢的人时就无法分班
代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Client { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine());// 多少次输入 String[] strs = new String[n]; for (int j = 0; j < n; j++) { strs[j] = br.readLine();// 两个不想在一起的小盆友 } boolean suc = true; HashSet<String> class1 = new HashSet<>(); HashSet<String> class2 = new HashSet<>(); for (String str : strs) { int ticket = calc(str,class1,class2); if(ticket == 0){ suc = false; break; } } if(suc){ System.out.println(1); }else { System.out.println(0); } } private static int calc(String str, HashSet<String> class1, HashSet<String> class2) { String[] split = str.split(" "); String one = split[0]; String two = split[1]; if(class1.contains(one) && class1.contains(two)){ return 0; } if(class2.contains(one) && class2.contains(two)){ return 0; } class1.add(one); class2.add(two); return 1; } }