A circular site with 300 columns of infinite rows. a B d represents the distance between a and B clockwise and d. Now I will give you some distance to determine whether there is a conflict, number of conflicting computing conflicts
Idea: weighted and query set
The distance between a and B is equal to the distance from B to the root node-the distance from a to the root node
1. When a and B are in the same set, compare the distance from B to the root node-the distance from a to the root node with the current input to see if the conditions are met.
2. When a and B are not in the same set, the two nodes are merged to update the distance.
Vector Method, the direction must be clear, the father points to the Son
If x's father rootx, y's father is rooty
Rootx --> x, rooty --> y is merged in the direction of rootx. The father of rootx is rooty, that is, rooty --> rootx
The distance between x --> y is d.
Rooty --> rootx = rootx --> x + x --> y + y --> rooty = rootx --> x + (-(y --> x )) + (-(rooty --> y ))
The merge direction varies with the format.
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int flag = 0; struct bian { int father; int dis; }p[50050]; void Make_set(int n) { int i; for(i = 1; i <= n; i++) { p[i].father = i; p[i].dis = 0; } } int Find_set(int x) { if(x != p[x].father) { int temp = p[x].father; p[x].father = Find_set(p[x].father); p[x].dis = ( p[x].dis + p[temp].dis) % 300; } return p[x].father; } void Union(int a,int b,int d) { int x = Find_set(a); int y = Find_set(b); if(x == y) { if(( (p[b].dis-p[a].dis+300) % 300 ) != d) { flag = 1; return ; } } else { p[x].father = y; p[x].dis = (p[b].dis+300-d-p[a].dis) % 300; } } int main() { int n,m; while(scanf("%d%d",&n,&m) != EOF) { int i,sum = 0; Make_set(n); for(i = 0; i < m; i++) { int a,b,d; flag = 0; scanf("%d%d%d",&a,&b,&d); Union(a,b,d); if(flag) sum++; } printf("%d\n",sum); } return 0; }