标签:向量 put code color const find http 简单题 return
http://hihocoder.com/problemset/problem/1515
题意:
思路:
带权并查集的简单题,计算的时候利用向量法则即可。
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 const int maxn = 100000+5; 5 6 int n,m,q; 7 int p[maxn],r[maxn]; 8 9 int finds(int x) 10 { 11 if(p[x]==x) return x; 12 int tmp = p[x]; 13 p[x] = finds(p[x]); 14 r[x] = r[x] + r[tmp]; 15 return p[x]; 16 } 17 18 void unions(int a, int b, int x, int y, int s) 19 { 20 p[x] = y; 21 r[x] = s+r[b]-r[a]; 22 } 23 24 int main() 25 { 26 //freopen("in.txt","r",stdin); 27 scanf("%d%d%d",&n,&m,&q); 28 for(int i=1;i<=n;i++) {p[i]=i;r[i]=0;} 29 while(m--) 30 { 31 int a,b,s; 32 scanf("%d%d%d",&a,&b,&s); 33 int x = finds(a); 34 int y = finds(b); 35 unions(a,b,x,y,s); 36 } 37 while(q--) 38 { 39 int a,b; 40 scanf("%d%d",&a,&b); 41 int x = finds(a); 42 int y = finds(b); 43 if(x!=y) puts("-1"); 44 else printf("%d\n",r[a]-r[b]); 45 } 46 return 0; 47 }
标签:向量 put code color const find http 简单题 return
原文地址:http://www.cnblogs.com/zyb993963526/p/7881584.html