Description
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 xiwill 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.
OutputPrint a single integer — the maximum possible danger.
题意:输入n和m,分别表示有n种化学原料,m种反应情况,向一个试管倒入化学药品,在没有化学反应的情况下危险度是1,只要有一种反应发生则危险度乘以2,求能达到的最大危险度。
思路:由输入建立一个无向图,最后用bfs搜索一遍看总共有多少边,则最大危险度就是2的边数次幂。
Sample Input
1 0
2 1
1 2
3 2
1 2
2 3
Sample Output
1
2
4
Hint
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).
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
bool a[60][60];
bool vis[60];
int n;
long long int cnt; //最后得数可能会超整型所以最好用长整型变量
void bfs(int x)
{
int y;
queue<int>q;
vis[x]=true;
q.push(x);
while(!q.empty())
{
y=q.front();
q.pop();
for(int i=1; i<=n; i++)
{
if(a[y][i]&&!vis[i])
{
cnt*=2; //只要搜到一条边就乘以2
vis[i]=true;
q.push(i);
}
}
}
return ;
}
int main()
{
int m,u,v;
while(~scanf("%d %d",&n,&m))
{
cnt=1;
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
for(int i=0; i<m; i++)
{
scanf("%d %d",&u,&v);
a[u][v]=true; //建立无向图
a[v][u]=true;
}
for(int i=1; i<=n; i++)
if(!vis[i])
{
bfs(i);
}
cout<<cnt<<endl; //用c++输出法可以避免输出类型的错误
}
return 0;
}<strong>
</strong>