[PAT顶级]1024 Currency Exchange Centers (35分)

分析:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值