How Many Answers Are Wrong HDU - 3038
考察: 带权并查集
做了银河英雄传说和奇偶游戏后这题应该算简单了,没加入集合的加入集合,已入集合的检验就行了
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 const int N = 80010; 6 vector<int> alls; 7 int p[N],d[N]; 8 struct query{ 9 int l,r,sum; 10 }query[N>>1]; 11 int findf(int x) 12 { 13 if(x!=p[x]){ 14 int t = findf(p[x]); 15 d[x]+=d[p[x]]; 16 p[x] = t; 17 } 18 return p[x]; 19 } 20 int findid(int x) 21 { 22 return lower_bound(alls.begin(),alls.end(),x)-alls.begin()+1; 23 } 24 int main() 25 { 26 //freopen("in.txt","r",stdin); 27 int n,m; 28 while(scanf("%d%d",&n,&m)!=EOF){ 29 int ans = 0; 30 alls.clear(); fill(d,d+N,0); 31 for(int i=1;i<=m;i++){ 32 scanf("%d%d%d",&query[i].l,&query[i].r,&query[i].sum); 33 query[i].l--; 34 alls.push_back(query[i].l); alls.push_back(query[i].r); 35 } 36 sort(alls.begin(),alls.end()); 37 alls.erase(unique(alls.begin(),alls.end()),alls.end()); 38 for(int i=1;i<=alls.size();i++) p[i] = i; 39 for(int i=1;i<=m;i++){ 40 int x = findid(query[i].l); int y = findid(query[i].r); 41 int px = findf(x); int py = findf(y); 42 if(px!=py){ 43 d[px] = d[y]-d[x]-query[i].sum; 44 p[px] = p[y]; 45 }else if(px==py&&d[y]-d[x]!=query[i].sum) ans++; 46 } 47 printf("%d\n",ans); 48 } 49 return 0; 50 }