题目大意
有一个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;
}