题目描述
blablabla
样例
blablabla
算法1
Java 代码
import java.io.*;
import java.util.*;
public class Main {
static class UFind {
int[] father;
int[] d;
UFind(int n){
father = new int[n+1];
d = new int[n+1];
for(int i = 1; i <= n; i++){
father[i] = i;
}
}
public 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 void union(int p, int q) {
int fp = find(p);
int fq = find(q);
if(fp != fq){
father[fp] = fq;
}
}
public 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;
}
public 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;
}
}
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
String[] s = read.readLine().split(" ");
int n = Integer.valueOf(s[0]);
int m = Integer.valueOf(s[1]);
UFind uf = new UFind(n);
int res = 0;
for(int i = 0; i < m; i++){
s = read.readLine().split(" ");
int d = Integer.valueOf(s[0]);
int f1 = Integer.valueOf(s[1]);
int f2 = Integer.valueOf(s[2]);
if(f1 > n || f2 > n){
res++;
continue;
}else if(d == 2 && f1 == f2) {
res++;
continue;
}else{
if (d == 1){
if (!uf.D1(f1, f2)){
res++;
continue;
}
}else if(d == 2){
if (!uf.D2(f1, f2)){
res++;
continue;
}
}
}
}
log.write(res + "\n");
log.flush();
}
}