城市建设

题意

n 个城市,m 条道路,每条道路有一个权值(可能为负),每个点有一个权值,表示修建码头的费用(为-1时表示不可以修建码头)。

题解

ans1不修建码头的最小生成树
ans2额外添加一个0号城市,将可建立码头的城市与它相连,求出的最小生成树
当不建码头也能联通时,答案为min(ans1,ans2),否则答案为 ans2

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <bits/stdc++.h>
#define forl(i, l, r) for (int i = l; i <= r; i++)
#define forr(i, r, l) for (int i = r; i >= l; i--)
#define for1(i, n) for (int i = 1; i <= n; i++)
#define for0(i, n) for (int i = 0; i < n; i++)
#define meminf(a) memset(a, inf, sizeof(a))
#define mem_1(a) memset(a, -1, sizeof(a))
#define mem0(a) memset(a, 0, sizeof(a))
#define inlld(lld) scanf("%lld", &lld)
#define inlf(f) scanf("%lf", &f)
#define ind(d) scanf("%d", &d)
#define ins(s) scanf("%s", s)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
typedef std::pair<long long, long long> pll;
typedef std::vector<long long> vll;
typedef std::pair<int, int> pii;
typedef unsigned long long ull;
typedef std::vector<int> vii;
typedef long double db;
typedef long long ll;
const db pi = acos((db)-1);
const ll inf =0x3f3f3f3f;
const ll mod = 1e9+7;
const int N = 2e5;
const db eps = 1e-8;
using namespace std;
int sign(db a) { return a < -eps ? -1 : a > eps; }
int db_cmp(db a, db b){ return sign(a-b); }

struct Edge{
int u,v,c;
Edge(){}
Edge(int a,int b,int _c){
u=a,v=b,c=_c;
}
bool operator <(const Edge y)const{
return c<y.c;
}
}edge[N];

int uni[N];
int find_r(int x){
if(x==uni[x])return x;
else return uni[x]=find_r(uni[x]);
}
int merge(Edge x){
int fa=find_r(x.u),fb=find_r(x.v);
if(fa!=fb){
uni[fa]=fb;
return 1;
}
if(x.c<0)return -1;
else return 0;
}
int main() {
#ifdef PerpEternal
// freopen("/Users/perpeternal/Documents/Sketch/data/in.dat", "r", stdin);
// freopen("/Users/perpeternal/Documents/Sketch/data/out.dat", "w", stdout);
#endif
//ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n,m,u,v,c,w,Size=0;
ll ans1=0,ans2=0;
scanf("%d%d",&n,&m);
for0(i,m){
scanf("%d%d%d",&u,&v,&c);
edge[Size++]=Edge(u,v,c);
}
for1(i,n)uni[i]=i;
sort(edge,edge+Size);
int cnt=0;
for0(i,Size){
switch(merge(edge[i])){
case 1:
ans1+=edge[i].c;
cnt++;
break;
case -1:
ans1+=edge[i].c;
}
}
for1(i,n){
ind(w);
if(w>0)edge[Size++]=Edge(0,i,w);
}
for1(i,n)uni[i]=i;
sort(edge,edge+Size);
for0(i,Size){
if(merge(edge[i]))ans2+=edge[i].c;
}
if(cnt==n-1)ans2=min(ans2,ans1);
printf("%lld\n",ans2);
return 0;
}