随笔-65  评论-6  文章-0  trackbacks-0
 1 /*
 2 Author:    Leo.W
 3 Descriptipn:  一个垃圾邮件判别系统。M a b 表示a、b具有相同内容,S a 表示对a存在误判,求最后内容相同邮件集合的数目。
 4 How to Do:    并查集,加入了一个新的操作是集合节点的删除,但由于集合内部元素关系的传递性,因此删除元素但保留由此元素
 5               带来的关系。所以不必删除结点,直接改头换面让被删除的结点在队末出现,重新开始,因此就用到了id数组。
 6   */
 7 #include <cstdio>
 8 #include <cstdlib>
 9 #define MAXSIZE 1000002
10 int n,m;//n个结点,m条路
11 int par[MAXSIZE],id[MAXSIZE],hasChild[MAXSIZE];
12 char ch;
13 
14 int findSet(int x){
15     if(x!=par[x])
16         par[x]=findSet(par[x]);
17     return par[x];
18 }
19 inline void merge(int x,int y){
20     x=findSet(x);
21     y=findSet(y);
22     if(x==y) return;
23     par[x]=y;//x变成附属
24     hasChild[y]+=hasChild[x];
25     hasChild[x]=0;//表示x只是y领衔的集合的一员
26 }
27 inline void makeSet(int n){
28     int i;
29     for(i=0;i<n;i++)//从0到n-1
30         par[i]=i,id[i]=i,hasChild[i]=1;
31 }
32 inline void scan(int &x){
33     while (ch=getchar(),ch<'0'||ch>'9');x=ch-'0';
34     while (ch=getchar(),ch>='0'&&ch<='9')x=x*10+ch-'0';
35 }
36 int main(){
37     //freopen("in.txt","r",stdin);
38     int no=1;
39     while (true){
40         scan(n);scan(m);
41         if(n==0&&m==0)    break;
42         makeSet(n);
43         int i,j;  int total=n;//用于队末扩展
44         char str;    int a,b;
45         for(i=0;i<m;i++){
46             str=getchar();
47             scan(a);
48             if(str=='M'){            
49                 scan(b);
50                 merge(id[a],id[b]);
51                 continue;
52             }
53             int fa=findSet(id[a]);
54             hasChild[fa]--;//原属集合内部元素数减少
55             id[a]=total;//映射被删除的结点,以后对a的操作,转为对total的操作
56             par[total]=total;//自立门户,即单独一个集合
57             hasChild[total]=1;
58             id[total]=total;//扩展方便最后统计
59             total++;
60         }
61         int sum=0;
62         for(j=0;j<total;j++)
63             if(hasChild[j]>0)    sum++;
64         printf("Case #%d: %d\n",no++,sum);
65     }    
66     return 0;
67  }
68 
posted on 2012-03-17 22:27 Leo.W 阅读(250) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理