1、LA 3644
题目:http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=12648
并查集入门题,寻找是否存在环,若存在,则cnt++
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> const int maxn=100010; using namespace std; int p[maxn]; //带路径压缩的并查集 int Find(int x){return p[x] == x?x:p[x]=Find(p[x]);} int main() { int x,y; while (scanf("%d",&x) == 1) { for (int i=0;i<maxn;i++) p[i]=i; int cnt=0; while (x != -1) { scanf("%d",&y); x=Find(x); y=Find(y); if (x == y) cnt++; else p[x]=y; scanf("%d",&x); } printf("%d\n",cnt); } return 0; }
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn=20010; int p[maxn]; int d[maxn]; int Find(int x) { if (p[x] != x) { int root=Find(p[x]); d[x] += d[p[x]]; return p[x]=root; } else return x; } int main() { int T; scanf("%d",&T); while (T--) { int n,u,v; char cmd[9]; scanf("%d",&n); for (int i=1;i<=n;i++) { p[i]=i; d[i]=0; } while (scanf("%s",cmd) && cmd[0] != 'O') { if (cmd[0] == 'I') { scanf("%d%d",&u,&v); p[u]=v; d[u]=abs(u-v) % 1000; } if (cmd[0] == 'E') { scanf("%d",&u); int t=Find(u); printf("%d\n",d[u]); } } } return 0; }