CodeForces 445B - DZY Loves Chemistry(并查集)
题意:给定n (1 <= n <= 50) 种试剂,给定m (0 <= m <= n*(n - 1) / 2) 组互相反应的试剂,现在有一个空容器危险度为1,每次反应会使危险度 * 2,求最大的危险度。
利用并查集找出有多少连通块,n - 连通块个数 即为反应次数。
#include<cstdio> #include<cstring> #include<cctype> #include<cstdlib> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<deque> #include<queue> #include<stack> #include<list> typedef long long ll; typedef unsigned long long llu; const int MAXN = 100 + 10; const int MAXT = 10000 + 10; const int INF = 0x7f7f7f7f; const double pi = acos(-1.0); const double EPS = 1e-6; using namespace std; int n, m, fa[MAXN]; void init(){ for(int i = 0; i < MAXN; ++i) fa[i] = i; } int find(int v){ return fa[v] = (fa[v] == v) ? v : find(fa[v]); } void merge(int a, int b){ int x = find(a), y = find(b); if(x < y) fa[y] = x; else fa[x] = y; } int main(){ scanf("%d%d", &n, &m); init(); int tmp1, tmp2; for(int i = 0; i < m; ++i){ scanf("%d%d", &tmp1, &tmp2); merge(tmp1, tmp2); } int no = 0; for(int i = 1; i <= n; ++i) if(fa[i] == i) ++no; printf("%I64d\n", 1ll << (n - no)); return 0; }