题目链接:http://acm.sdibt.edu.cn/vjudge/contest/view.action?cid=2209#problem/F
!a b w 表示b比a大w
? a b 输出b比a大多少
#include<iostream> using namespace std; const int maxn = 100005; int fa[maxn],val[maxn]; int find_(int x){ if(x != fa[x]) { int t=fa[x]; fa[x]=find_(fa[x]); val[x]+=val[t]; return fa[x]; }//路径压缩 return x; } void merge_(int a,int b,int c){ int fx,fy; fx=find_(a); fy=find_(b); if(fx != fy) { fa[fx]=fy; val[fx]=val[b]+c-val[a]; } } int main(){ int n,m; while(cin>>n>>m&&n&&m){ char t; int a,b,c; for(int i=1;i<=m;i++) fa[i]=i,val[i]=0; while(m--){ cin>>t>>a>>b; if(t == '!') { cin>>c; merge_(a,b,c); } else { int fx,fy; fx=find_(a),fy=find_(b); if(fx != fy) cout<<"UNKNOWN"<<endl; else cout<<val[a]-val[b]<<endl; } } } }