CodeForces - 445B - DZY Loves Chemistry

先上题目:

B. DZY Loves Chemistry
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

DZY loves chemistry, and he enjoys mixing chemicals.

DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.

Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.

Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

Input

The first line contains two space-separated integers n and m .

Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.

Consider all the chemicals numbered from 1 to n in some order.

Output

Print a single integer — the maximum possible danger.

Sample test(s)
input
1 0
output
1
input
2 1
1 2
output
2
input
3 2
1 2
2 3
output
4
Note

In the first sample, there's only one way to pour, and the danger won't increase.

In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.

In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

 

  题意:给出n种材料,m对关系,有关系的材料相遇会反应,按照不同的顺序将n种材料放进反应炉里面,如果某一种材料放进去的时候炉里面已经有可以与它反应的材料,就结果*2(其实结果为1),问最大的结果是多少?这一题的做法使用并查集来做,这题可以抽象成一个图,往里面放点,当有点放入的时候发现图里面有边可以到达它,结果就乘以2,那总的结果其实就是每一个连通分量的点数减1再乘以2,然后每一个连通分量的结果相加。用并查集将所有的连通分量找出来,然后计算结果就可以了。

 

上代码:

 1 #include <bits/stdc++.h>
 2 #define LL long long
 3 #define MAX 52
 4 using namespace std;
 5 
 6 int p[MAX];
 7 int ss[MAX];
 8 
 9 int findset(int x){ return p[x]==x ? x : p[x] = findset(p[x]);}
10 
11 void unionset(int y,int x){
12     y=findset(y);
13     x=findset(x);
14     p[y]=x;
15 }
16 
17 void resetset(int n){
18     for(int i=0;i<=n;i++) p[i]=i;
19 }
20 
21 int main()
22 {
23     int n,m,a,b;
24     ios::sync_with_stdio(false);
25     //freopen("data.txt","r",stdin);
26     while(cin>>n>>m){
27             resetset(n);
28         for(int i=0;i<m;i++){
29             cin>>a>>b;
30             unionset(a,b);
31         }
32         memset(ss,0,sizeof(ss));
33         for(int i=1;i<=n;i++){
34             int o=findset(i);
35             ss[o]++;
36         }
37         LL ans=1;
38         for(int i=1;i<=n;i++){
39             if(ss[i]>0) ss[i]--;
40             ans=ans<<ss[i];
41         }
42         cout<<ans<<endl;
43     }
44     return 0;
45 }
445B

 

posted @ 2014-07-11 17:14  海拉鲁的林克  阅读(278)  评论(0编辑  收藏  举报