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 by2. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
The first line contains two space-separated integers n andm
.
Each of the next m lines contains two space-separated integersxi andyi(1 ≤ xi < yi ≤ n). These integers mean that the chemicalxi will react with the chemicalyi. Each pair of chemicals will appear at most once in the input.
Consider all the chemicals numbered from 1 to n in some order.
Print a single integer — the maximum possible danger.
1 0
1
2 1 1 2
2
3 2 1 2 2 3
4
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
int f[500];
int n,m;
void Init(int n)
{
for(int i=1;i<=n;i++)
f[i] = i;
}
int Find(int x)
{
return x == f[x] ? x : f[x] = Find(f[x]);
}
void Merge(int x,int y)
{
int Fx = Find(x);
int Fy = Find(y);
if(Fx != Fy)
f[Fx] = Fy;
}
int main()
{
while(cin>>n>>m)
{
Init(n);
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
Merge(x,y);
}
LL sum = 1;
for(int i=1;i<=n;i++)
{
if(f[i] != i)
sum *= 2;
}
cout<<sum<<endl;
}
}#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
bool vis[500];
bool Map[500][500];
int n,m;
LL sum;
void BFS(int x)
{
queue<int >que;
vis[x] = true;
que.push(x);
while(!que.empty())
{
int t = que.front();
que.pop();
for(int i=1;i<=n;i++)
{
if(!vis[i] && Map[t][i])
{
sum *= 2;
vis[i] = true;
que.push(i);
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(vis,false,sizeof(vis));
memset(Map,false,sizeof(Map));
sum = 1;
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
Map[x][y] = Map[y][x] = true;
}
for(int i=1;i<=n;i++)
{
if(!vis[i])
BFS(i);
}
cout<<sum<<endl;
}
return 0;
}

本文探讨了如何通过最优顺序混合化学物质以达到试管中最大危险度的问题。具体包括输入化学物质数量及其反应对的数据结构定义,以及使用并查集算法实现的两种不同方法来求解最大危险度。
712

被折叠的 条评论
为什么被折叠?



