分析:
MST题目,不过这次题目不像之前那样先提前按权值排好序即可以,而是每次选取边权尽可能小,同时选取的center在之前尽可能出现过。先将所有的边放入优先队列,重定义<运算符,同时用一个unordered_set来保存遍历过的center,每次从队列取出来的一定就是符合题意的了(之前以为优先队列不能动态监视<运算符涉及到的容器,从而进行队列元素的自动调整,现在发现还真行)
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 1e4 + 10;
const int inf = 0x3f3f3f3f;
unordered_set<string> se;
struct edge
{
int x, y;
string s;
int val;
edge(int a = 0, int b = 0, string c = "", int d = 0) : x(a), y(b), s(c), val(d){}
bool operator < (const edge b) const
{
return val != b.val ? val > b.val : se.find(s) == se.end();
}
}e[maxn << 1];
int n, m;
priority_queue<edge> q;
set<string> res1;
int fa[maxn];
int res2;
vector<edge> res3;
int find(int x)
{
return fa[x] = x == fa[x] ? x : find(fa[x]);
}
void kruscal()
{
int cnt = 0;
while(!q.empty())
{
edge now = q.top(); q.pop();
int x = now.x, y = now.y;
int fx = find(x), fy = find(y);
if(fx == fy) continue;
fa[fx] = fy;
res2 += now.val;
res3.push_back(now);
se.insert(now.s);
cnt++;
if(cnt == n - 1)
{
return;
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) fa[i] = i;
for(int i = 1; i <= m; i++)
cin >> e[i].x >> e[i].y >> e[i].s >> e[i].val, q.push(e[i]);
kruscal();
cout << se.size() << " " << res2 << endl;
sort(res3.begin(), res3.end(), [](const edge &a, const edge &b){
return a.s != b.s ? a.s < b.s : a.val < b.val;
});
for(edge &x : res3)
cout << x.x << " " << x.y << " " << x.s << ' ' << x.val << endl;
}