Description
现在给出了一个简单无向加权图。你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的
最小生成树。(如果两颗最小生成树中至少有一条边不同,则这两个最小生成树就是不同的)。由于不同的最小生
成树可能很多,所以你只需要输出方案数对31011的模就可以了。
Input
第一行包含两个数,n和m,其中1<=n<=100; 1<=m<=1000; 表示该无向图的节点数和边数。每个节点用1~n的整
数编号。接下来的m行,每行包含两个整数:a, b, c,表示节点a, b之间的边的权值为c,其中1<=c<=1,000,000,0
00。数据保证不会出现自回边和重边。注意:具有相同权值的边不会超过10条。
Output
输出不同的最小生成树有多少个。你只需要输出数量对31011的模就可以了。
Sample Input
4 6
1 2 1
1 3 1
1 4 1
2 3 2
2 4 1
3 4 1
Sample Output
8
题解:
考虑克鲁斯卡尔算法,每次都在剩余的权值最小的边里随便选一条两端点不连通的边,题目里权值相同的边不超过十条,所以我们可以直接按克鲁斯卡尔算法暴力枚举每条边,为了便于把连上的边断开,并查集不用压缩路径。
PS:MST中共有k种边,我开始ZZ的从小到大枚举大小为前k种的边wa了好久TAT
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<stack>
#include<map>
using namespace std;
const int maxx = 1e3 + 5;
const int mod = 31011;
long long sum = 0;
struct Edge
{
int x, y, z;
}a[maxx];
bool cmp(Edge x, Edge y)
{
return x.z < y.z;
}
struct rg
{
int l, r, dat;
}r[maxx];
int fa[maxx];
int get(int x)
{
if(fa[x] == x)
return x;
return get(fa[x]);
}
inline void mg(int x, int y)
{
fa[get(x)] = get(y);
}
void init(int n)
{
for(int i = 1; i <= n; ++i)
fa[i] = i;
}
void dfs(int l, int r, int k, int num)
{
if(l > r)
{
if(k == num)
sum++;
return;
}
int x = get(a[l].x), y = get(a[l].y);
if(x != y)
{
mg(x, y);
dfs(l+1, r, k+1, num);
fa[x] = x, fa[y] = y;
}
dfs(l+1, r, k, num);
}
map<int, int >mmp;
int main()
{
int n, m;
cin>>n>>m;
init(n);
for(int i = 0; i < m; ++i)
cin>>a[i].x>>a[i].y>>a[i].z;
sort(a, a + m, cmp);
int tot = 0;
for(int i = 0; i < m; ++i)
{
if(get(a[i].x) != get(a[i].y))
{
mg(a[i].x, a[i].y);
tot++;
mmp[a[i].z]++;
}
}
if(tot != n-1)
{
cout<<0<<endl;
return 0;
}
r[0].l = 0;
r[0].dat = a[0].z;
int u = 0;
long long res = 1;
for(int i = 1; i < m; ++i)
{
if(a[i].z != a[i-1].z)
{
r[u].r = i-1, r[++u].l = i;
r[u].dat = a[i].z;
}
}
r[u].r = m-1;
init(n);
for(int i = 0; i <= u; ++i)
{
sum = 0;
if(!mmp[r[i].dat])
continue;
dfs(r[i].l, r[i].r, 0, mmp[r[i].dat]);
for(int j = r[i].l; j <= r[i].r; ++j)
if(get(a[j].x) != get(a[j].y))
mg(a[j].x, a[j].y);
res = res * sum % mod;
}
cout<<res<<endl;
return 0;
}