AcWing 240. 食物链java
原题链接
中等
作者:
蜗牛爱吃草
,
2020-04-29 21:13:26
,
所有人可见
,
阅读 685
import java.io.*;
public class FoodChain {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
String[] params = in.readLine().split(" ");
int n = Integer.parseInt(params[0]);
int k = Integer.parseInt(params[1]);
init(n);
int res = 0;
for(int i = 0; i < k; i++) {
String[] op = in.readLine().split(" ");
int opnum = Integer.parseInt(op[0]);
int x = Integer.parseInt(op[1]);
int y = Integer.parseInt(op[2]);
if (x > n || y > n){
res++;
}else{
if (opnum == 1){
if (!D1(x,y)){
res++;
}
}else{
if (!D2(x,y)){
res++;
}
}
}
}
System.out.println(res);
in.close();
}
static int N = 50010;
static int M = 3;
static int[] father = new int[N];
static int[] d = new int[N];
public static void init(int n){
for (int i = 1; i <= n; i++) {
father[i] = i;
}
}
public static int find(int x){
if (father[x] != x){
int u = find(father[x]);
d[x] += d[father[x]];
father[x] = u;
}
return father[x];
}
public static boolean D1(int x,int y){
int fx = find(x);
int fy = find(y);
if (fx == fy){
if ((d[x] - d[y]) % 3 == 0){
return true;
}else{
return false;
}
}
father[fx] = fy;
d[fx] = d[y] - d[x];
return true;
}
/**
* x吃y
* @param x
* @param y
* @return
*/
public static boolean D2(int x,int y){
int fx = find(x);
int fy = find(y);
if (fx == fy){
if ((d[x] - d[y] - 1) % 3 == 0){
return true;
}else{
return false;
}
}
father[fx] = fy;
d[fx] = d[y] - d[x] + 1;
return true;
}
}