poj1703

此题是比较明显的并查集应用 本来不想用 优化路径 因为那样可以通过搜索深度知道与根节点的关系 但是超时 

然后想到用rank 但感觉好麻烦

千呼万唤始出来的是一个想法记录其他的那个帮派的集合用getfather[i]判断是否是一个gang 通过getfather(i+MAX)去查询另外一个gang 每次一个D 就union两次 

1 #include <iostream>
2 using namespace std;
3
4 const int MAX = 100000;
5 int father[2*MAX];
6 int n;
7
8 void init()
9 {
10 for(int i=1;i<=n+MAX;i++)
11 father[i] = i;
12 }
13
14 int getfather(int v)
15 {
16 if(father[v]==v)return v;
17 return father[v] = getfather(father[v]);
18 }
19
20 void Union(int x,int y)
21 {
22 int fx,fy;
23 fx = getfather(x);
24 fy = getfather(y);
25 if(fx==fy)return;
26 else
27 father[fx] = fy;
28 }
29
30 int main()
31 {
32 int T;
33 int m;
34 scanf("%d",&T);
35 char ch;
36 int i,j;
37 while(T--)
38 {
39 scanf("%d%d",&n,&m);
40 init();
41 scanf("%c",&ch);
42 while(m--)
43 {
44 scanf("%c%d%d",&ch,&i,&j);
45 if(ch=='D')
46 {
47 Union(i,MAX+j);
48 Union(j,i+MAX);
49 }
50 else
51 {
52 if(getfather(i)==getfather(j))cout<<"In the same gang."<<endl;
53 else if(getfather(i)==getfather(i+MAX) || getfather(j)==getfather(i+MAX))cout<<"In different gangs."<<endl;
54 else cout<<"Not sure yet."<<endl;
55 }
56 scanf("%c",&ch);
57 }
58 }
59 system("pause");
60 return 0;
61
62 }

posted @ 2011-06-09 13:33  dapanshe  阅读(1584)  评论(2编辑  收藏  举报