SDU 程序设计思维与实践 Week6 C 掌握魔法の东东 I【图重构】

题意描述

东东在老家农村无聊,想种田。农田有 n 块,编号从 1~n。种田要灌溉
众所周知东东是一个魔法师,他可以消耗一定的 MP 在一块田上施展魔法,使得黄河之水天上来。他也可以消耗一定的 MP 在两块田的渠上建立传送门,使得这块田引用那块有水的田的水。 (1<=n<=3e2)
黄河之水天上来的消耗是 Wi,i 是农田编号 (1<=Wi<=1e5)
建立传送门的消耗是 Pij,i、j 是农田编号 (1<= Pij <=1e5, Pij = Pji, Pii =0)
东东为所有的田灌溉的最小消耗

输入描述

第1行:一个数n
第2行到第n+1行:数wi
第n+2行到第2n+1行:矩阵即pij矩阵

输出描述

东东最小消耗的MP值

样例输入

4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0

样例输出

9

思路描述

如果没有“黄河之水天上来”,那么这是一个MST问题。现在我们只需要加入一个超级源点,使他连接每一个点,权值为 W i W_i Wi.然后对这n+1个点执行克鲁斯卡尔算法

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=3e2+10;
int n;
struct Edge{
	int u,v,w;
	bool operator <(const Edge& e) const{
		return w<e.w;
	}
}; 
Edge Es[maxn*maxn];
int tot;
//并查集
int par[maxn];
void init(int n){
	for(int i=0;i<=n;i++){
		par[i]=i;
	}
} 
int find(int x){
	return par[x]==x? x:par[x]=find(par[x]);
}
bool unite(int x,int y){
	x=find(x),y=find(y);
	if(x==y) return false;
	par[x]=y;
	return true;
}
int Kruskal(){
	init(n);	
	sort(Es,Es+tot);	
	int cnt=0,ans=0;
	for(int i=0;i<tot;i++){
		if(unite(Es[i].u,Es[i].v)){
			ans+=Es[i].w;
			if(++cnt==n){
				return ans;
			}
		}
	}
	return -1;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>Es[tot].w;
		Es[tot].u=0;
		Es[tot].v=i;
		tot++;
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>Es[tot].w;
			if(i==j) continue;
			Es[tot].u=i;
			Es[tot].v=j;
			tot++;			
		}
	}	

	cout<<Kruskal()<<endl;
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值