标签:pst html ext tar 通过 记录 decide pre code
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 42463 | Accepted: 13065 |
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4
Not sure yet.
In different gangs.
In the same gang.
(爷爷,父亲) | (父亲,儿子) | (爷爷,儿子) |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
定义:fx 为 x的根节点, fy 为 y 的根节点,联合时,使得fa[ fx ] = fy;同时也要寻找 fx 和 fy 的关系,其关系为(r[ x ] + 1 - r[ y ]) % 2;
因为确定了 x 和 y 的关系是 1 ,因此 r[ fy ] = (r[ x ] + 1 - r[ y ]) % 2;
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100005; int fa[maxn*3]; int find(int x) { int r = x; while (r != fa[r]) r = fa[r]; int i = x,j; while (i != r) { j = fa[i]; fa[i] = r; i = j; } return r; } void unite(int x,int y) { x = find(x),y = find(y); if (x != y) fa[x] = y; } bool same(int x,int y) { return find(x) == find(y); } int main() { int T; scanf("%d",&T); while (T--) { int N,M,x,y; char opt[5]; scanf("%d%d",&N,&M); for (int i = 0;i <= 3*N;i++) fa[i] = i; while (M--) { scanf("%s %d %d",opt,&x,&y); if (opt[0] == ‘A‘) { if (find(x) == find(y)) printf("In the same gang.\n"); else if (same(x,y + N) && same(x + N,y)) printf("In different gangs.\n"); else printf("Not sure yet.\n"); } else if (opt[0] == ‘D‘) { unite(x,y + N); unite(x + N,y); } } } return 0; }
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100005; int fa[maxn],r[maxn]; int find(int x) { if (fa[x] == x) return fa[x]; int tmp = fa[x]; fa[x] = find(fa[x]); r[x] = (r[tmp] + r[x]) % 2; return fa[x]; } void unite(int x,int y) { int fx = find(x),fy = find(y); if (fx == fy) return; fa[fy] = fx; r[fy] = (r[x] + 1 - r[y]) % 2; } int main() { int T; scanf("%d",&T); while (T--) { int N,M,x,y; char opt[5]; scanf("%d%d",&N,&M); for (int i = 0;i <= N;i++) fa[i] = i,r[i] = 0; while (M--) { scanf("%s %d %d",opt,&x,&y); if (opt[0] == ‘A‘) { if (find(x) == find(y)) { if (r[x] == r[y]) printf("In the same gang.\n"); else printf("In different gangs.\n"); } else printf("Not sure yet.\n"); } else unite(x,y); } } return 0; }
POJ 1703 Find them, Catch them(带权并查集)
标签:pst html ext tar 通过 记录 decide pre code
原文地址:http://www.cnblogs.com/zzy19961112/p/6043420.html