POJ - 1679 The Unique MST(惟一最小生成樹)

題目連接:

  https://vjudge.ppsucxtt.cn/problem/POJ-1679node

思路:

     將最小生成樹求出之後,再去掉生成樹上的每一條邊求最小生成樹權值,若是仍然存在權值和本來的最小生成樹權值相等,說明最小生成樹並不惟一。  
 注意:可能不存在最小生成樹,即有的點沒有邊相連,也視爲其餘輸出"Not Unique!"

代碼:

#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iomanip>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 110;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

struct node //存邊結構體
{
    int l, r;
    ll w;
    bool operator<(const node &u) const
    {
        return w < u.w;
    }
} a[N * N];

int f[N];

int find(int x)
{
    if (x != f[x])
        f[x] = find(f[x]);
    return f[x];
}

int n, m, del;
bool flag;
vector<int> edge;

ll Kruskal()
{
    for (int i = 1; i <= n; i++)
        f[i] = i;
    int k = n - 1;
    ll ans = 0;
    for (int i = 1; i <= m; i++)
    {
        if (i == del)
            continue;
        int f1 = find(a[i].l), f2 = find(a[i].r);
        if (f1 != f2)
        {
            if (del == -1)
                edge.push_back(i);
            k--;
            f[f1] = f2;
            ans += a[i].w;
        }
        if (!k)
            break;
    }
    if (k)
        return INF;
    return ans;
}

int main()
{
    fastio;
    int T;
    cin >> T;
    while (T--)
    {
        cin >> n >> m;
        flag = false, del = -1;
        for (int i = 1; i <= m; i++)
            cin >> a[i].l >> a[i].r >> a[i].w;
        sort(a + 1, a + m + 1);
        ll ans = Kruskal();
        if (ans == INF)
        {
            cout << "Not Unique!" << endl;
            edge.clear();
            continue;
        }
        for (int i = 0; i < edge.size(); i++)
        {
            del = edge[i];
            ll t = Kruskal();
            if (ans == t)
            {
                flag = true;
                break;
            }
        }
        if (flag)
            cout << "Not Unique!" << endl;
        else
            cout << ans << endl;
        edge.clear();
    }

    return 0;
}
相關文章
相關標籤/搜索