Codeforces Round #254 (Div. 2) B DZY Loves Chemistry
题目链接:http://codeforces.com/contest/445/problem/B
题意:有n个化学药品,有m中能反应,空试管的危险系数是1,加入药品后,如果能反应,试管的危险系数就*2,(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)刚开始这句理解错了。
思路:并查集,相同集合里元素是能反应的(个数是q),就*2。所以结果就是 2^q。
注意:数据范围要用 __int64
代码:
#include<stdio.h>
int father[2000];
int count;
int find(int x)
{
if(x==father[x])
return x;
return father[x]=find(father[x]);
}
void merge(int x,int y)
{
int fx,fy;
count=0;
fx=find(x);
fy=find(y);
if(fx!=fy)
{
father[fx]=fy;
}
}
int main()
{
int n,m;
int i,a,b;
while(scanf("%d %d",&n,&m)!=EOF)
{
if(m==0)
{
printf("1\n");
continue;
}
for(i=1;i<=n;i++)
father[i]=i;
for(i=0;i<m;i++)
{
scanf("%d %d",&a,&b);
merge(a,b);
}
__int64 ans=1;
for(i=1;i<=n;i++)
{
if(father[i]!=i)//在同一个集合中。
ans*=2;
}
printf("%I64d\n",ans);
}
return 0;
}