题意:
让你最小花费,使得图连通。
本题有两种特殊的边。
- 每个点可以建立 航空站 或者 港口
- 对于建立 航空站的点,两两之间可以到达。
- 对于建立 港口的点,两两之间可以到达。
思路:
我们可以
建立两个虚拟点:
- n + 1 n+1 n+1航空中心
-
n
+
2
n+2
n+2海运中心
之后连边,跑生成树。
航空中心 和 海运中心可建,可不建。
这里我们可以枚举。
AC
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <cmath>
#include <cstring>
#define For(i,x,y) for(int i = (x); i <= (y); i ++ )
#define fori(i,x,y) for(int i = (x); i < (y); i ++ )
#define sz(a) (int)a.size()
#define ALL(a) a.begin(), a.end()
#define mst(x,a) memset(x,a,sizeof(x))
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define db double
#define endl '\n'
#define debug(a) cout << #a << ": " << a << endl
using namespace std;
typedef long long LL;
typedef long long ll;
typedef unsigned long long ULL;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
typedef pair<int,int>pa;
typedef pair<ll,ll>pai;
typedef pair<db,db> pdd;
const db eps = 1e-6;
const db pi = acos(-1.0);
template<typename T1, typename T2> void ckmin(T1 &a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> void ckmax(T1 &a, T2 b) { if (a < b) a = b; }
int read() {
int x = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f |= ch == '-', ch = getchar();
while (isdigit(ch)) x = 10 * x + ch - '0', ch = getchar();
return f ? -x : x;
}
template<typename T> void print(T x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
template<typename T> void print(T x, char let) {
print(x), putchar(let);
}
template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }
const int maxn = 200000 + 6;
struct Edge{
int a, b, w;
bool operator < (const Edge e) const {
return w < e.w;
}
};
int n, m;
vector<Edge> e;
int p[maxn];
void init_p(){
for(int i = 1; i <= n+2; i ++ ) p[i] = i;
}
int find(int x){
if(p[x] == x) return x;
return p[x] = find(p[x]);
}
bool merge(int a, int b){
int fa = find(a), fb = find(b);
if(fa == fb) return false;
p[fa] = fb;
return true;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++ ) {
int x;
cin>> x;
e.push_back({i,n+1,x});
}
/*
y
*/
for(int i = 1; i <= n; i ++ ) {
int y;
cin>> y;
e.push_back({i,n+2,y});
}
for(int i = 1; i <= m; i ++ ) {
int a, b, w;
cin >> a >>b >> w;
e.push_back({a,b,w});
}
sort(e.begin(), e.end());
ll ans = INF;
for(int bitmask = 0; bitmask < 4; bitmask ++ ) {
init_p();
ll sum = 0, cnt = 1;
for(auto [a,b,w]: e){
bool fl = true;
if(b == n+1 && (bitmask&1) == 0) {
fl = false;
}
if(b==n+2 && (bitmask>>1&1) == 0) {
fl = false;
}
if(fl) {
if(merge(a,b)) sum += w, cnt++;
}
if(n + __builtin_popcount(bitmask) == cnt) break;
}
if(cnt == n + __builtin_popcount(bitmask))ans = min(ans, sum);
}
cout << ans << endl;
return 0;
}