Luo Gu P1892 [BOI2003] gang (kind disjoint-set)

Portal

Problem-solving ideas

With disjoint-set f keep friendships, a memory array e enemies of relations, is an auxiliary array, so called species disjoint-set.

When p and q are friends, the direct merger, but when the enemy, take some action.

When the enemy has not p (i.e., p is the enemy), direct e [p] = q;

Otherwise put p and q are the enemies become friends, which is tantamount to p and q become enemies.

Of course, the same is true for q.

Final tally how many people are ancestors, that their friends are his statistics down.

AC Code

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 const int maxn=1005;
 5 int f[maxn],e[maxn];
 6 int n,m;
 7 char c;
 8 int find(int x){
 9     if(f[x]==x) return x;
10     return f[x]=find(f[x]);
11 }
12 int ans;
13 int main(){
14     cin>>n>>m;
15     for(int i=1;i<=n;i++) f[i]=i,e[i]=i;
16     for(int i=1;i<=m;i++){
17         int p,q;
18         cin>>c>>p>>q;
19         if(c=='F'){
20             f[find(p)]=find(q);
21         }
22         else{
23             if(e[p]==p)e[p]=find(q);
24             else f[find(e[p])]=find(q);
25             if(e[q]==q)e[q]=find(p);
26             else f[find(e[q])]=find(p);
27         }
28     }
29     for(int i=1;i<=n;i++){
30         if(f[i]==i) ans++;
31     }
32     cout<<ans;
33     return 0;
34 }

 

Guess you like

Origin www.cnblogs.com/yinyuqin/p/11402628.html