HDOJ 1856 More is better

Problem Description
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.

Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
 


 

Input
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
 


 

Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
 


 

Sample Input
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
 


 

Sample Output
4
2
Hint
A and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect). In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
    这题的意思很简单,要求最多有多少个点是连通的,可用并查集或者搜索。我的做法是dfs+邻接表,第一次用vector模拟了下邻接表,感觉效果还可以,要是STL的效率能再高点,就完美了。(但是这是不可能的)
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 vector< vector<int> > map;
 6 int n,ans,cnt;
 7 bool visited[100001];
 8 
 9 void dfs(int u){
10     visited[u]=true;
11     for(int i=0;i<map[u].size();i++)
12         if(!visited[map[u][i]])
13             cnt++,dfs(map[u][i]);
14 }
15 int main(){
16     int u,v,i,m;
17     while(scanf("%d",&n)!=EOF){
18         map.clear();
19         map.resize(100001);
20         memset(visited,false,sizeof(visited));
21         for(m=i=0;i<n;i++){
22             scanf("%d %d",&u,&v);
23             m=m>? m:u;
24             m=m>? m:v;
25             map[u].push_back(v),map[v].push_back(u);
26         }
27         for(ans=i=1;i<=m;i++){
28             if(!visited[i])
29                 cnt=1,dfs(i);
30             ans=ans>cnt ? ans:cnt;
31         }
32         printf("%d\n",ans);
33     }
34     return 0;
35 }

posted on 2009-04-27 16:34 极限定律 阅读(460) 评论(0)  编辑 收藏 引用 所属分类: ACM/ICPC


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


<2009年5月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(10)

随笔分类

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜