1016 Uniqueness of MST (35 分)
解题思路:
本题重点在于如何判断最小生成数是否唯一,可以先随便生成一个最小生成树,这时候n个点是由n-1条边连起来的(如果不连通的情况判断一下直接输出),那如果这时候我们枚举所有未使用过的边(在生成树的过程中进行标记),将这条边加进原来的最小生成树中,必然会形成一个环,这时候我们就要断开一条边,使得环断开,那么我们可以发现如果这个环里面有任一条边的权值=我们新加的那条边的权值,那就说明这时候断开两条边的任一条边都能够重新组成最小生成树(显然环中的边权值不会大于新加的边的权值),即存在新的一颗最小生成树。
值得注意的是,这时候找环不需要那么麻烦,比如现在枚举的边起点是s,终点是e,权值是w,我们只要找到从s到e的路径上是否有边的权值=w即可。
代码:
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define pb push_back
#define G 6.67430*1e-11
#define rd read()
#define pi 3.1415926535
using namespace std;
const ll mod = 1e9 + 7;
const int MAXN = 30000005;
const int MAX2 = 300005;
inline ll read() {
ll x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch>'9') {
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
ll fpow(ll a, ll b)
{
ll ans = 1;
while (b)
{
if (b & 1)ans = ans * a % mod;
b >>= 1;
a = a * a % mod;
}
return ans;
}
int n;
struct ss
{
int s, e, w, use;
}x[200005];
bool cmp(ss a, ss b) { return a.w < b.w; }
int fa[505];
int find(int r) { return fa[r] == r ? r : fa[r] = find(fa[r]); }
vector<pii> v[505];
int sum = 0;
void join(int i)
{
int fx = find(x[i].s), fy = find(x[i].e);
if (fx != fy)
{
fa[fx] = fy;
x[i].use = 1;
sum += x[i].w;
v[x[i].s].push_back(mp(x[i].e, x[i].w));
v[x[i].e].push_back(mp(x[i].s, x[i].w));
}
}
int vis[505];
int f = 0;
bool dfs(int end, int now, int cost)
{
if (now == end)
{
return true;
}
for (int i = 0; i < v[now].size(); i++)
{
if (!vis[v[now][i].first])
{
vis[v[now][i].first] = 1;
if (dfs(end, v[now][i].first, cost))
{
if (cost == v[now][i].second)f = 1;
return true;
}
}
}
return false;
}
signed main()
{
int n = rd, m = rd;
int i;
for (int i = 1; i <= n; i++)fa[i] = i;
for (i = 0; i < m; i++)
{
x[i].s = rd, x[i].e = rd, x[i].w = rd;
x[i].use = 0;
}
sort(x, x + m,cmp);
for (int i = 0; i < m; i++)
{
join(i);
}
int c = 0;
for (int i = 1; i <= n; i++)
{
if (find(i) == i)c++;
}
if (c > 1)
{
cout << "No MST" << endl << c;
return 0;
}
for (int i = 0; i < m; i++)
{
if (!x[i].use)
{
vis[x[i].s] = 1;
dfs(x[i].e, x[i].s, x[i].w);
if (f)break;
}
}
cout << sum << endl << (!f ? "Yes" : "No");
return 0;
}