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)
东东为所有的田灌氵的最小消耗

Input

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

Output

东东最小消耗的MP值

Example

Input

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

Output

9

思路

对于为每块地降雨的MP消耗看作是一块0号田地到该田地引流的MP消耗,因此将田地的数量看作是n+1块。然后将此问题建模成为一个加权无向图的生成树问题,使用kruskal算法,在所有的加权边中,找到权重最小的边,如果加入选中该边之后形成环(使用并查集,如果该边的两个顶点已经在两个同一个并查集中,则为形成环),则将此边删除,之后重复上述过程,直到将所有的边遍历完成。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=4e2+10;
int a[maxn],result=0;
void ini(){for(int i=0;i<maxn;i++) a[i]=i;}
struct edge
{
    int u,v,mp;
    //edge *next;
    bool operator<(edge e){return mp<e.mp;}
    bool operator>(edge e){ return mp>e.mp;}
}e[(maxn+1)*maxn/2];
int find(int x)
{
    int y=x;
    while(x!=a[x])
        x=a[x];
    while(y!=x)
    {
        int temp=y;
        y=a[y];
        a[temp]=x;
    }
return x;
}
void unite(int x,int y)
{ 
    int temp=find(y);
    a[temp]=find(x);
}
int main()
{
    ini();
    int n,count=0;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        e[i-1].u=0;
        e[i-1].v=i;
        int temp=0;
        cin>>temp;
        e[i-1].mp=temp;
    }
    count=n;
    for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)
    {
    	int temp=0;
    	cin>>temp;
    	if(i<j)
    	{
    		e[count].u=i;
    		e[count].v=j;
    		e[count].mp=temp;
    		count++;
		}
	}
    sort(e,e+count);
    for(int i=0;i<count;i++)
    {
    	int u=e[i].u,v=e[i].v,mp=e[i].mp;
    	if(find(u)!=find(v))
    	{
       	 	unite(u,v);
       		result+=mp;
    	}
	}
    cout<<result<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值