【最小生成树】Jungle Roads POJ - 1251

Jungle Roads POJ - 1251

题意:

给定若干条村庄之间的道路及其维护费用,问可以保证各村庄之间连通的最低维护费用。

思路:

直接套最小生成树的板子。

int fa[maxn];
int r[maxn];
int x[maxn], y[maxn], w[maxn];
int num;

int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
bool cmp(int i, int j) { return w[i] < w[j]; };
char alpha[] = { "0ABCDEFGHIJKLMNOPQRSTUVWXYZ" };

int solve() {
    int ans = 0;
    for (int i = 0; i < maxn; i++) fa[i] = i;
    for (int i = 0; i < num; i++) r[i] = i;
    sort(r, r + num, cmp);
    for (int i = 0; i < num; i++) {
        int e = r[i];
        int u = find(x[e]);
        int v = find(y[e]);
        if (u != v) {
            ans += w[e];
            fa[u] = v;
        }
    }
    return ans;
}

int main()
{
    //ios::sync_with_stdio(false);
    int n;
    map<char, int> mp;
    for (int i = 1; i <= 26; i++) mp[alpha[i]] = i;
    while (cin >> n && n) {
        num = 0;
        for (int i = 1; i <= n - 1; i++) {
            char ch1, ch2; int k,weight; cin >> ch1 >> k;
            while (k--) {
                x[num] = mp[ch1];
                cin >> ch2 >> weight;
                y[num] = mp[ch2];
                w[num] = weight;
                num++;
            }
        }
        cout << solve() << endl;
    }
    return 0;
}
posted @ 2020-08-14 00:00  StreamAzure  阅读(78)  评论(0编辑  收藏  举报