牛客多校8 - Interesting Computer Game(并查集)

题目链接:点击查看

题目大意:给出两个数组 a[ i ]  和 b[ i ],每次可以从 a[ i ] 和 b[ i ] 中选择一个数,求最后选出的数中,不同的数的个数最多

题目分析:比赛时用网络流乱搞水过去了,但是现在都不知道为什么那样建图能过

正解是并查集,将每对 a[ i ] 和 b[ i ] 视为一条边后,n 条边连接之后,会出现数个连通块,对于每个连通块我们分两种情况讨论:

  1. 连通块是个树:有 n 个点和 n - 1 条边,因为每条边最多选一个点,所以 n - 1 条边最多只能选 n - 1 个点
  2. 连通块存在至少一个环:那么此时 n 个点的话至少有 n 条边了,肯定存在一种方法可以将连通块中的所有点都选一遍

所以实现的话,可以用带权并查集,维护父节点的同时顺便维护一个布尔变量 circle ,代表当前的连通块内是否有环,数据较大需要离散化,我是 map 离散化,因为用 map 的话可以在线离散化

代码:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=2e5+100;

int f[N],cnt;

bool circle[N];

unordered_map<int,int>mp;

int find(int x)
{
	return f[x]==x?x:f[x]=find(f[x]);
}

void merge(int x,int y)
{
	int xx=find(x),yy=find(y);
	if(xx!=yy)
	{
		f[xx]=yy;
		circle[yy]|=circle[xx];
	}
	else
		circle[xx]=true;
}

void init()
{
	mp.clear();
	cnt=0;
	for(int i=0;i<N;i++)
	{
		f[i]=i;
		circle[i]=false;
	}
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	int w;
	cin>>w;
	int kase=0;
	while(w--)
	{
		init();
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			if(!mp[x])
				mp[x]=++cnt;
			if(!mp[y])
				mp[y]=++cnt;
			merge(mp[x],mp[y]);
		}
		int ans=cnt;
		for(int i=1;i<=cnt;i++)
			if(f[i]==i&&!circle[i])
				ans--;
		printf("Case #%d: %d\n",++kase,ans);
	}









    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/107776260