【bzoj1202】 HNOI2005—狡猾的商人
http://www.lydsy.com/JudgeOnline/problem.php?id=1202 (题目链接)
题意
给出m段区间和,判断是否存在某段区间与之前读入的区间相矛盾。
Solution
裸带权并查集。
代码
// bzoj1202 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<cmath> #define LL long long #define inf 2147483640 #define Pi 3.1415926535898 #define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout); using namespace std; int fa[10010],m,n,T,r[10010]; int find(int x) { if (x==fa[x]) return x; int f=find(fa[x]); r[x]=r[x]+r[fa[x]]; fa[x]=f; return f; } bool Union(int x,int y,int w) { int r1=find(x),r2=find(y); if (r1==r2) { if (w!=r[y]-r[x]) return 1;} else { fa[r2]=r1; r[r2]=w+r[x]-r[y]; } return 0; } int main() { scanf("%d",&T); while (T--) { bool flag=1; scanf("%d%d",&n,&m); for (int i=0;i<=n;i++) fa[i]=i,r[i]=0; while (m--) { int x,y,w; scanf("%d%d%d",&x,&y,&w); x--; if (Union(x,y,w)) {flag=0;break;} } if (flag) printf("true\n"); else printf("false\n"); } return 0; }
This passage is made by MashiroSky.