1016: [JSOI2008]最小生成树计数
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 5893 Solved: 2395
[ Submit][ Status][ Discuss]
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,000。数据保证不会出现自回边和重边。注意:具有相同权值的边不会超过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
结论题:
所有不同的最小生成树,长度相同的边数量一定都相同
这样先求发最小生成树找出每条边用多少次,之后再搜一遍就好了
注意:
①因为有回溯,所以并查集不能将结点直接连接到根,必须保证连的是它父亲
②按长度搜索时,一定要按从短到长的顺序搜
因为并查集连的都是父亲,所以复杂度O(n*m)
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct Road
{
int u, v;
int len;
bool operator < (const Road &b) const
{
if(len<b.len)
return 1;
return 0;
}
}Road;
Road s[1005];
int ans, sum, ufs[105], p[2005];
int Find(int x)
{
if(ufs[x]==0)
return x;
return Find(ufs[x]);
}
void Sech(int now, int r, int x)
{
int t1, t2;
if(now>r)
{
if(x==0)
sum++;
return;
}
t1 = Find(s[now].u), t2 = Find(s[now].v);
if(t1!=t2)
{
ufs[t1] = t2;
Sech(now+1, r, x-1);
ufs[t1] = ufs[t2] = 0;
}
Sech(now+1, r, x);
}
int main(void)
{
int n, m, i, t1, t2, ca, cb;
while(scanf("%d%d", &n, &m)!=EOF)
{
memset(p, 0, sizeof(p));
memset(s, 0, sizeof(s));
memset(ufs, 0, sizeof(ufs));
for(i=1;i<=m;i++)
scanf("%d%d%d", &s[i].u, &s[i].v, &s[i].len);
sort(s+1, s+m+1);
ans = 1, sum = ca = cb = 0;
for(i=1;i<=m;i++)
{
cb++;
t1 = Find(s[i].u);
t2 = Find(s[i].v);
if(t1!=t2)
{
ufs[t1] = t2;
ca++, sum++;
}
if(s[i].len!=s[i+1].len)
{
p[i-cb+1] = cb;
p[i] = ca*10000;
ca = cb = 0;
}
}
if(sum<n-1)
{
printf("0\n");
continue;
}
memset(ufs, 0, sizeof(ufs));
for(i=1;i<=m;i++)
{
if(p[i]!=0 && p[i]<10000 && p[i+p[i]-1]>=10000)
{
sum = 0;
Sech(i, i+p[i]-1, p[i+p[i]-1]/10000);
ans = (ans*sum)%31011;
}
t1 = Find(s[i].u);
t2 = Find(s[i].v);
if(t1!=t2)
ufs[t1] = t2;
}
printf("%d\n", ans);
}
return 0;
}