题目:I.Interesting Computer Game
分析:
参考博客
简单来说就是将每个数字看成一个点,然后每一对数可以连一条边,最后对于每个连通分支,如果有环,则结果只能+=该联通分支的点数,否则结果+=点数-1
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 2e6;
const int inf = 0x3f3f3f3f;
#define PAIR pair<int, int>
vector<int> v;
int v1[maxn], v2[maxn];
int fa[maxn], siz[maxn], edge[maxn], vis[maxn];
int n;
int getid(int x)
{
return lower_bound(v.begin(), v.end(), x) - v.begin() + 1;
}
int find(int x)
{
return fa[x] = fa[x] == x ? x : find(fa[x]);
}
int main()
{
int t; cin >> t;
int cases = 0;
while (t--)
{
cin >> n;
v.clear();
for (int i = 1; i <= n; i++)
{
cin >> v1[i] >> v2[i];
v.push_back(v1[i]), v.push_back(v2[i]);
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
for(int i = 1; i <= v.size(); i++)
fa[i] = i, siz[i] = 1, edge[i] = 0 ,vis[i] = 0;
for(int i = 1; i <= n; i++)
{
int fx = find(getid(v1[i])), fy = find(getid(v2[i]));
if(fx == fy) edge[fx]++;
else
{
fa[fx] = fy;
siz[fy] += siz[fx];
edge[fy] += edge[fx] + 1;
}
}
int res = 0;
for(int i = 1; i <= v.size(); i++)
{
int f = find(i);
if(vis[f]) continue;
vis[f] = 1;
res += (siz[f] > edge[f] ? siz[f] - 1 : siz[f]);
}
printf("Case #%d: %d\n", ++cases, res);
}
}