[BOI2003] gang

Title Description

1920 Chicago, there was a group of bandits. If the two robbers met, then they are either friends or enemies. And one thing is certain, that is:

My friend's friend is my friend;

My enemy's enemy is my friend.

Two robbers condition is the same gang if and only if they are friends. Now to give you some information about the robbers, you have to ask the maximum number of bandit gangs.

Input and output formats

Input formats:

The first line of the input file is an integer gangs.in N (2 <= N <= 1000), represents the number of robbers (numbered from 1 to N). The second line M (1 <= M <= 5000), indicates the number of pieces of information about the robbers. The following M rows, each row may be F pq or E pq (1 <= p q <= N), F represents p and q are friends, E is p and q are the enemy. Input data to ensure that no conflicting information.

Output formats:

Output file gangs.out only one line that indicates the maximum number of groups possible.

Sample input and output

Input Sample # 1:
6
4
E 1 4
F 3 5
F 4 6
E 1 2
Output Sample # 1:
3 

Analysis:
this question as a basis for the investigation and has become the subject sets will be disjoint-set training topics, more classic, code implementation is relatively simple, basically naked disjoint-set the template. As long as one can judge before the merger

CODE:
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 using namespace std;
 7 int n,m,f[1005];  
 8 int t[1005],ans,x[1005]; 
 9 int find(int k){
10     if(f[k]==k)return k;
11     return f[k]=find(f[k]);
12 }
13 void merge(int x,int y){
14     x=find(f[x]);
15     y=find(f[y]);
16     f[x]=y;
17     return ;
18 }
19 int main(){
20      cin>>n>>m;
21      for(int i=1;i<=n;i++)
22         f[i]=i;
23     for(int i=1;i<=m;i++){
24         char c;
25         int p,q;
26         cin>>c>>p>>q;
27         if(c=='F') 
28         merge(p,q);  
29         else{
30             if(x[p]==0) 
31             x[p]=find(q);
32             else 
33             merge(q,x[p]); 
34             if(x[q]==0) 
35             x[q]=find(p);
36             else 
37             merge(p,x[q]);
38         } 
39     }
40     for(int i=1;i<=n;i++)
41         t[find(i)]++;
42     for(int i=1;i<=n;i++)
43         if(t[i]) ans++; 
44     cout<<ans;
45     return 0;
46  } 
 
  

 

 

Guess you like

Origin www.cnblogs.com/kanchuang/p/11128672.html