题目链接: 传送门
DZY Loves Chemistry
time limit per test:1 second memory limit per test:256 megabytes
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 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 Input
1 0
2 1
1 2
3 2
1 2
2 3
Sample Output
1
2
4
思路:
题目大意:给你n种化学物品,其中有的化学物品能反应,若加入一种化学物品能与试管中已有的物品反应,则危险值×2,问最大的危险值。
最大危险值很明显是2^(n-v),其中“v”为连通块的个数。比如1-6六个数,1-3、4-5、6分为三个连通块,显然只有在同一个连通块里的化学物品能反应。
#include <cstdio>
using namespace std;
int n, m, fa[100], x, y;
int gf(int x)
{
if (fa[x] != x) fa[x] = gf(fa[x]);
return fa[x];
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--)
{
scanf("%d%d", &x, &y);
fa[gf(x)] = gf(y);
}
long long ans = (1LL << n);
for (int i = 1; i <= n; i++)
if (gf(i) == i) ans /= 2;
printf("%I64d\n", ans);
}
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef __int64 LL;
int ans[55];
int N,M;
void init()
{
for (int i = 1;i <= N;i++)
{
ans[i] = i;
}
}
int main()
{
while (~scanf("%d%d",&N,&M))
{
int u,v;
LL res = 1;
memset(ans,0,sizeof(ans));
init();
while (M--)
{
scanf("%d%d",&u,&v);
while (u != ans[u])
{
u = ans[u];
}
while (v != ans[v])
{
v = ans[v];
}
if (u != v)
{
res *= 2;
}
ans[v] = u;
}
printf("%I64d\n",res);
}
return 0;
}