POJ 1182 食物链
传送门:
解题思路:
一个带权的并查集。
推荐博客:http://blog.csdn.net/niushuai666/article/details/6981689
实现代码:
#include <iostream> #include <cstdio> using namespace std; const int maxn=50000+10; int p[maxn],r[maxn]; int findfa(int x){ if(x==p[x]) return x; int t=p[x]; p[x]=findfa(p[x]); r[x]=(r[x]+r[t])%3; return p[x]; } void unit(int x,int y,int d){ int fx=findfa(x); int fy=findfa(y); if(fx==fy) return; p[fy]=fx; r[fy]=(r[x]+d+3-r[y])%3; } void init(int n){ for(int i=0;i<=n;i++){ p[i]=i; r[i]=0; } } int main(){ int N,K; scanf("%d%d",&N,&K); init(N); int ans=0; while(K--){ int d,x,y; scanf("%d%d%d",&d,&x,&y); if(x>N||y>N){ ans++; continue; } if(d==2&&x==y){ ans++; continue; } int fx=findfa(x); int fy=findfa(y); if(fx!=fy){ unit(x,y,d-1); }else{ if(d==1&&r[x]!=r[y]){ ans++; continue; } if(d==2&&(r[y]+3-r[x])%3!=d-1){ ans++; continue; } } } printf("%d\n",ans++); }
自己选的路,跪着也要把它走完------ACM坑