【bzoj2753】[SCOI2012]滑雪與時間膠囊 最小生成樹

遇到一個比較有意思的題目,寫出來看看。

如果沒有高度相等的點,那麼就是一個有向無環圖的最小樹形圖,貪心的讓每一個點選入邊中權值最小的就可以

加上了高度相等的點後,變成了部分無向的最小樹形圖,或者說是一個分層後的最小生成樹

因爲,層與層之間的邊都是有向的,而同一層之間的邊都是無向的

如何定義層這個概念呢?高度相等的點就是一層

用一種比較巧妙的方式來做最小生成樹,就可以避免處理層之間的問題

對邊排序時,按照點的高度爲第一關鍵字,邊的權值爲第二關鍵字排序

這樣上一層的節點都處理完後,再處理下一層的節點,就可以把層與層之間的有向邊看成無向邊了


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#define maxn 100010
#define maxm 2000010

using namespace std;

struct yts
{
	int x,y;
	long long z;
}e[maxm];

int head[maxn],to[maxm],next[maxm];
bool vis[maxn];
int h[maxn],f[maxn],q[maxn];
int n,m,num,cnt;
long long ans;

void addedge(int x,int y,int z)
{
	num++;to[num]=y;next[num]=head[x];head[x]=num;e[num]=(yts){x,y,z};
}

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

bool cmp(yts x,yts y)
{
	return h[x.y]>h[y.y] || (h[x.y]==h[y.y] && x.z<y.z);
}

void bfs()
{
	int l=0,r=1;
	q[1]=1;vis[1]=1;cnt=1;
	while (l<r)
	{
		int x=q[++l];
		for (int p=head[x];p;p=next[p])
		  if (!vis[to[p]]) q[++r]=to[p],vis[to[p]]=1,cnt++;
	}
}

int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n;i++) scanf("%d",&h[i]);
	for (int i=1;i<=m;i++)
	{
		int x,y;long long z;
		scanf("%d%d%lld",&x,&y,&z);
		if (h[x]>=h[y]) addedge(x,y,z);
		if (h[y]>=h[x]) addedge(y,x,z);
	}
	bfs();
	printf("%d ",cnt);
	for (int i=1;i<=n;i++) f[i]=i;
	sort(e+1,e+num+1,cmp);
	for (int i=1;i<=num;i++)
	{
		int x=e[i].x,y=e[i].y;
		if (!vis[x] || !vis[y]) continue;
		int f1=find(x),f2=find(y);
		if (f1!=f2) f[f1]=f2,ans+=e[i].z;
	}
	printf("%lld\n",ans);
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章