https://ac.nowcoder.com/acm/contest/330/G
C++版本一
题解:
std
最小生成树
看成一张图,就是把同类元素的试剂当作一个点之后,求这个图的最小生成树。
然后用你最喜欢的求MST的算法求解就好。注意判不连通的情况。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m ,k;
cin >> n >> m >> k;
vector<int> a(n);
for (auto& t : a) cin >> t, --t;
vector<int> fa(k);
iota(fa.begin(), fa.end(), 0);
function<int(int)> find = [&](int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); };
auto unite = [&](int u, int v) { fa[find(u)] = find(v); };
vector<tuple<int, int, int>> edges;
for (int i = 0, u, v, c; i < m; i++)
{
cin >> u >> v >> c;
--u, --v;
edges.emplace_back(c, a[u], a[v]);
}
sort(edges.begin(), edges.end());
long long ans = 0;
int cnt = 0;
int c, u, v;
for (auto& e : edges)
{
tie(c, u, v) = e;
if (find(u) == find(v)) continue;
unite(u, v);
ans += c;
if (++cnt == k - 1) break;
}
if (cnt == k - 1)
cout << ans << endl;
else
cout << -1 << endl;
}
扫一扫,把题目装进口袋
C++版本二
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=200000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,q,x,y,c;
ll ans,cnt,flag,temp;
int a[N];
int pre[N];
char str;
struct node{
int x,y,c;
bool operator<(const node&S)const{
return c<S.c;
}
}e[N];
int find(int x){
if(x==pre[x])
return x;
return pre[x]=find(pre[x]);
}
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
scanf("%d%d%d",&n,&m,&k);
//scanf("%d",&t);
//while(t--){}
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&e[i].c);
e[i].x=a[x];
e[i].y=a[y];
}
sort(e+1,e+m+1);
for(int i=1;i<=k;i++)
pre[i]=i;
for(int i=1;i<=m;i++){
int fx=find(e[i].x);
int fy=find(e[i].y);
if(fx!=fy){
pre[fx]=fy;
ans+=e[i].c;
}
}
for(int i=1;i<=k;i++)
if(pre[i]==i)
cnt++;
if(cnt==1)
cout << ans << endl;
else
cout<<-1<<endl;
//cout << "Hello world!" << endl;
return 0;
}