【bzoj1016】 JSOI2008—最小產生樹計數

來源:互聯網
上載者:User

標籤:

http://www.lydsy.com/JudgeOnline/problem.php?id=1016 (題目連結)

題意:求圖的最小產生樹計數。

Solution 
  %了下題解,發現要寫矩陣樹,150++的程式什麼鬼。於是就蒯了hzwer的簡便方法。 
  將邊按照權值大小排序,將權值相同的邊分到一組,統計下每組分別用了多少條邊。然後對於每一組進行dfs,判斷是否能夠用這一組中的其他邊達到相同的效果。最後把每一組的方案數相乘就是答案。 
  注意並查集不要壓縮路徑,不然的話不好回溯。

代碼:

// bzoj1016#include<algorithm>#include<iostream>#include<cstdlib>#include<cstring>#include<cstdio>#include<cmath>#define LL long long#define inf 2147483640#define MOD 31011#define Pi acos(-1.0)#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);using namespace std;int getint() {    int f=1,x=0;char ch=getchar();    while (ch<=‘0‘ || ch>‘9‘) {if (ch==‘-‘) f=-1;ch=getchar();}    while (ch>=‘0‘ && ch<=‘9‘) {x=x*10+ch-‘0‘;ch=getchar();}    return x*f;}const int maxn=1010;struct edge {int u,v,w;}e[maxn<<2],a[maxn];int fa[maxn],sum,n,m,cnt,tot;bool cmp(edge a,edge b) {    return a.w<b.w;}int find(int x) {    return fa[x]==x ? x : find(fa[x]);}void dfs(int x,int now,int k) {    if (now==a[x].v+1) {        if (k==a[x].w) sum++;        return;    }    int r1=find(e[now].u),r2=find(e[now].v);    if (r1!=r2) {        fa[r1]=r2;        dfs(x,now+1,k+1);        fa[r1]=r1,fa[r2]=r2;    }    dfs(x,now+1,k);}int main() {    scanf("%d%d",&n,&m);    for (int i=1;i<=m;i++) scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);    for (int i=1;i<=n;i++) fa[i]=i;    sort(e+1,e+1+m,cmp);    for (int i=1;i<=m;i++) {        if (e[i].w!=e[i-1].w) {a[++cnt].u=i;a[cnt-1].v=i-1;}        int r1=find(e[i].u),r2=find(e[i].v);        if (r1!=r2) {fa[r1]=r2;a[cnt].w++;tot++;}    }    a[cnt].v=m;    if (tot!=n-1) {printf("0");return 0;}    for (int i=1;i<=n;i++) fa[i]=i;    int ans=1;    for (int i=1;i<=cnt;i++) {        sum=0;        dfs(i,a[i].u,0);        ans=(ans*sum)%MOD;        for (int j=a[i].u;j<=a[i].v;j++) {            int r1=find(e[j].u),r2=find(e[j].v);            if (r1!=r2) fa[r1]=r2;        }    }    printf("%d",ans);    return 0;}

  

【bzoj1016】 JSOI2008—最小產生樹計數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.