【Kickstart】2019 Round E - Cherries Mesh

解法

就是想求最小生成樹,但是邊的權重只有1和2,而且給出了權重爲1的邊,剩餘邊權重都爲2
顯然,可以用最小生成樹的某個算法,權重爲1的邊只加上那些能聯通兩個不同集合的邊
輸入完畢之後會得到k個聯通分量,需要k-1條權重爲2的邊,所以ans要再加上2(k-1)

#include <stdio.h>
#include <string>
#include <iostream>
#include <memory.h>
#include <stdlib.h>
#include <cmath>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <functional>

#define MAXN 100010
#define NINF -100000
#define INF 65536


using namespace std;

typedef long long lld;

int n,m;
int f[MAXN];

int find(int x) {
    int r = x;
    while(f[r]!=r) {
        r = f[r];
    }
    while(f[x]!=r) {
        int tmp = f[x];
        f[x] = r;
        x = tmp;
    }
    return r;
}

lld solve() {
    lld ans = 0;
    int solitude = n;
    for(int i=1;i<=n;++i)
        f[i] = i;
    int x,y;
    for(int i=0;i<m;++i) {
        scanf("%d%d", &x,&y);
        int rx = find(x), ry = find(y);
        if(rx!=ry) {
            ans++;
            f[rx] = ry;
            solitude--;
        }
    }
    ans += ((lld)solitude-1)*2;
    return ans;
}

int main() {
    int t;
    scanf("%d",&t);
    for(auto round=1;round<=t;++round) {
        scanf("%d%d",&n,&m);
        printf("Case #%d: %lld\n",round,solve());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章