CodeForce 445 B.DZY Loves Chemisty(そして、検索集)

4523 ワード

転載は出典を明記してください。http://blog.csdn.net/u012860063?view mode=contensts
テーマリンク:http://codeforces.com/problemset/problem/445/B
----------------------------------------------------------------------------------------------------------------------------------------------------------
                http://user.qzone.qq.com/593830943/main
 
 
----------------------------------------------------------------------------------------------------------------------------------------------------------
DZY loves chemistry、and he enjoys mixing chemicars.
DZY has n chemicars,and m pairs of them will react.He wants to pour these chemicars into a test tube,and he needs to pour them in one by,in any order.
Let's consider the danger of a test tube.Danger of an empty test tube is 1.And everry time when DZY pours a chemical、if there re already one or more chemicars in the test tube that can react with it、the danger of the test tube will multipled by 2.Otherwise the danger remans as it is.
Find the maximm possible danger after pouring all the chemicars one by in optimal order.
Input
The first line contains two space-separated integers n and m  .
Each of the next m LINE contains two space-separated integers xi。 and yi (1̵≦̵xi𔎅<𔎅yi≦𔎅n).The e integers mean that the chmical xi。 will react with the chemical yi.Each pair of chemical will appar at most once in the input.
Consinder all the chemicars numberred from 1 ト n in some order.
Output
Print a single integer-the maximum possible danger.
Sample test(s)
input
1 0
out put
1
input
2 1
1 2
out put
2
input
3 2
1 2
2 3
out put
4
ノート
In the first sample,there's only one way to pour,and the danger won't increase.
In the second sample,no mater we pour the 1 st chemical first、or pour the 2 nd chemical first,the answer is always 2.
In the third sample、there are four ways to achieve the maximbossible danger:2-3、2-3、1-3 and 3-1(that is the numbers of the chemicars in order of pouring)。
コードは以下の通りです
#include <cstdio>
#include <cmath>
int father[1005];
int find(int x)
{
    return x==father[x]?x:father[x]=find(father[x]);
}
void Union(int x,int y)
{
    int f1=find(x);
    int f2=find(y);
    if(f1!=f2)
    {
        father[f2]=f1;
    }
}
int main()
{
    int n,m,a,b;
    int i, j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i = 1 ; i <=n ; i++ )
            father[i] = i ;
        if(m == 0)
        {
            printf("1
"); continue; } int k=0; for(i = 0 ; i < m ; i++ ) { scanf("%d%d",&a,&b); Union(a,b); } __int64 msum = 1; for(i=1 ; i <= n ; i++) if(father[i]==i) k++; int ans = n - k; msum = pow(2,ans); printf("%I64d
",msum); } return 0 ; }