2020杭电多校第二场 Total Eclipse

第一题: Total Eclipse

题目:

There are n cities and m bidirectional roads in Byteland. These cities are labeled by 1,2,…,n, the brightness of the i-th city is bi.

Magician Sunset wants to play a joke on Byteland by making a total eclipse such that the brightness of every city becomes zero. Sunset can do the following operations for arbitrary number of times:

· Select an integer k (1≤k≤n).

· Select k distinct cities c1,c2,…,ck (1≤ci≤n) such that they are connected with each other. In other words, for every pair of distinct selected cities ci and cj (1≤i

· For every selected city ci (1≤i≤k), decrease bci by 1.

Note that Sunset will always choose k with the maximum possible value. Now Sunset is wondering what is the minimum number of operations he needs to do, please write a program to help him.

思路

我们先按照点的大小从大到小进行排序,然后每次就填点,查询它所连的点是否被加入,如果加入了,那么就搜寻一下查询点的祖先是否是这个点,如果不是,就让查询点的祖先的父亲变成这个点,这样就会构成有根树。
然后我们就会发现如果某个点成为最小值,他的父亲已经进行了x次操作,那么我们的答案就是这个点的值减去他父亲节点的值。

代码

#include
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;

const int N=1e5+7,M=4e5+8;

int n,m;
int h[N],e[M],ne[M],idx;
int f[N],q[N],fa[N];
int a[N];
bool visit[N];

void add(int a,int b)
{
	e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

int find(int x)
{
	if(x!=f[x])
	{
		f[x]=find(f[x]);
	}
	return f[x];
}

int cmp(int x,int y)
{
	return a[x]>a[y];
}

int main()
{
	//freopen("test.in","r",stdin);//设置 cin scanf 这些输入流都从 test.in中读取
    //freopen("test.out","w",stdout);//设置 cout printf 这些输出流都输出到 test.out里面去
	//ios::sync_with_stdio(false);
	//cin.tie(0),cout.tie(0);
	int T;
	cin>>T;
	while(T--)
	{
		memset(h,-1,sizeof h);
		memset(visit,0,sizeof visit);
		memset(fa,0,sizeof fa);
		scanf("%d%d",&n,&m);
		idx=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			f[i]=q[i]=i;
		}
		
		for(int i=1;i<=m;i++)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			add(x,y),add(y,x);
		}
		
		sort(q+1,q+1+n,cmp);
		
		for(int i=1;i<=n;i++)
		{
			int u=q[i];
			visit[u]=1;
			for(int j=h[u];~j;j=ne[j])
			{
				int k=e[j];
				if(!visit[k]) continue;
				int v=find(k);
				if(v==u) continue;
				f[v]=fa[v]=u;
			}
		}
		ll ans=0;
		for(int i=1;i<=n;i++)
		{
			ans+=a[i]-a[fa[i]];
		}
		printf("%lld\n",ans);
	}
	return 0;
}

你可能感兴趣的:(图论,2020杭电多校)