[bzoj5101] [POI2018]Powód

題目大意

有一個n*m的網格圖,給定相鄰的格子之間牆的高度,並且默認邊界的牆的高度是無窮大的。再給定水位上限H,問有多少種可能的水位。

n*m≤500000 H≤1,000,000,000

分析

可以把每個格子看成一個點,相鄰的點之間有邊權爲牆高度的邊,然後求一次最小生成樹。
在克魯斯卡爾算法過程中,當兩個點在一個聯通塊時,水位一定是一樣的。
那麼再設Ans[x]表示聯通塊x當前的答案。新加入一條邊時,合併一下兩個Ans。

時間複雜度是O(nmlognm)

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int N=1e6+5,mo=1e9+7;

typedef long long LL;

int n,m,H,ans,sum,f[N],D[N],tot,cnt,now[N],Ans[N];

struct Edge
{
    int x,y,v;
}A[N];

bool operator < (Edge a,Edge b)
{
    return a.v<b.v;
}

char c;

int read()
{
    int x=0,sig=1;
    for (c=getchar();c<'0' || c>'9';c=getchar()) if (c=='-') sig=-1;
    for (;c>='0' && c<='9';c=getchar()) x=x*10+c-48;
    return x*sig;
}

int Get(int x)
{
    for (D[tot=1]=x;f[D[tot]]!=D[tot];tot++) D[tot+1]=f[D[tot]];
    for (int i=1;i<tot;i++) f[D[i]]=D[tot];
    return D[tot];
}

int Id(int x,int y)
{
    return (x-1)*m+y;
}

int main()
{
    freopen("data.in","r",stdin);
    n=read(); m=read(); H=read();
    for (int i=1;i<=n;i++) for (int j=1;j<m;j++)
    {
        A[++sum].x=Id(i,j); A[sum].y=Id(i,j+1); A[sum].v=read();
    }
    for (int i=1;i<n;i++) for (int j=1;j<=m;j++)
    {
        A[++sum].x=Id(i,j); A[sum].y=Id(i+1,j); A[sum].v=read();
    }
    sort(A+1,A+sum+1);
    cnt=n*m;
    ans=1;
    for (int i=1;i<=cnt;i++) f[i]=i,now[i]=-1;
    for (int i=1,j=1,p,q;i<=sum;i++) if (i==sum || A[i].v<A[i+1].v)
    {
        for (;j<=i;j++)
        {
            p=Get(A[j].x); q=Get(A[j].y);
            if (p!=q)
            {
                f[q]=p; Ans[p]=(Ans[p]+A[i].v-now[p])%mo; Ans[q]=(Ans[q]+A[i].v-now[q])%mo;
                Ans[p]=(LL)Ans[p]*Ans[q]%mo; now[p]=A[i].v;
            }
        }
    }
    ans=1;
    for (int i=1;i<=cnt;i++) if (f[i]==i) ans=(LL)ans*(Ans[i]+H-now[i])%mo;
    printf("%d\n",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章