P5687 [CSP-SJX2019] 网格图(Kruskal扩展)

题目链接

在这里插入图片描述
Kruskal 思想的扩展,一开始想到了贪心取各行各列中的最小边权,但是没有把握好环的判断问题,只敲了个裸的 Kruskal 水了水,后面参考了洛谷第一篇的题解,其实就是简单地记录一下已经取的行/列的数目就行啦…

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=310*310;
const int maxm=310*310*2;
int n,m,tot,idx=0,f[maxn],a[maxn/2],b[maxn/2];
struct Edge{
	int from,to,dis;
	Edge(){}
	Edge(int ff,int tt,int dd):from(ff),to(tt),dis(dd){}
	bool operator<(const Edge &e)const{return dis<e.dis;}
}edge[maxm];

int father(int x){
	while(x!=f[x]){
		f[x]=f[f[x]];
		x=f[x];
	}
	return x;
}

void unionfather(int x,int y){
	f[father(y)]=father(x);
}

void Kruskal(){
	for(int i=1;i<=tot;i++)
		f[i]=i;
	sort(edge,edge+idx);
	ll ans=0,cnt=0;
	for(int i=0;i<idx;i++){
		if(cnt==tot-1)
			break;
		if(father(edge[i].from)!=father(edge[i].to)){
			unionfather(edge[i].from,edge[i].to);
			ans=(ll)ans+(ll)edge[i].dis;
			cnt++;
		}
	}
	printf("%lld\n",ans);
} 

int main()
{
	scanf("%d%d",&n,&m);
	tot=n*m; 
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		int from,to=(i-1)*m+1;
		for(int j=1;j<m;j++){		
			from=to;
			to=from+1;
			edge[idx++]=Edge(from,to,a[i]);
		}
	}		
	for(int i=1;i<=m;i++){
		scanf("%d",&b[i]);
		int from,to=i;
		for(int j=1;j<n;j++){
			from=to;
			to=from+m;
			if(to>tot) break;
			edge[idx++]=Edge(from,to,b[i]);
		}
	}	
	Kruskal();
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=3e5+10;
int n,m,a[maxn],b[maxn];
ll ans;
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);		
	for(int j=1;j<=m;j++)
		scanf("%d",&b[j]);	
	sort(a+1,a+1+n);
	sort(b+1,b+1+m);	
	ans=(ll)a[1]*(m-1)+(ll)b[1]*(n-1);
	int i=2,j=2,row=1,col=1;
	while(i<=n&&j<=m){
		if(a[i]<=b[j]){
			ans+=(ll)a[i++]*(m-col);
			row++;
		}
		else{
			ans+=(ll)b[j++]*(n-row);
			col++;
		}
	}
	printf("%lld",ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值