做法
注意到上下左右都联通答案是1,都不连通答案是黑格数的次幂。
判掉后发现只有一边联通很好做,矩阵乘法上就行了。
#include<cstdio>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
typedef long long ll;
const int mo=1000000007;
char s[1050][1050];
int sta[80];
int a[2][2],ans[2][2],dis[2][2],o[2][2];
int i,j,l,t,n,m,top,cnt,t1,t2,p1,p2,num;
ll k;
char get(){
char ch=getchar();
while (ch!='.'&&ch!='#') ch=getchar();
return ch;
}
int qsm(int x,ll y){
if (!y) return 1;
int t=qsm(x,y/2);
t=(ll)t*t%mo;
if (y%2) t=(ll)t*x%mo;
return t;
}
void mult(int a[2][2],int b[2][2],int c[2][2]){
int i,j,k;
fo(i,0,1)
fo(j,0,1)
o[i][j]=0;
fo(k,0,1)
fo(i,0,1)
fo(j,0,1)
o[i][j]=(o[i][j]+(ll)a[i][k]*b[k][j]%mo)%mo;
fo(i,0,1)
fo(j,0,1)
c[i][j]=o[i][j];
}
int main(){
scanf("%d%d%lld",&n,&m,&k);
fo(i,1,n)
fo(j,1,m){
s[i][j]=get();
if (s[i][j]=='#'){
cnt++;
if (j>1&&s[i][j-1]=='#') t1++;
if (i>1&&s[i-1][j]=='#') t2++;
}
}
fo(i,1,n)
if (s[i][1]=='#'&&s[i][m]=='#') p1++;
fo(i,1,m)
if (s[1][i]=='#'&&s[n][i]=='#') p2++;
if (p1<p2){
swap(p1,p2);
swap(t1,t2);
}
if (k==1||p2){
printf("1\n");
return 0;
}
if (!p1&&!p2){
printf("%d\n",qsm(cnt,k-1));
return 0;
}
if (k==2){
printf("%d\n",cnt-t1);
return 0;
}
fo(i,0,1) ans[i][i]=1;
a[0][0]=cnt-t1;a[0][1]=-p1;
dis[0][0]=cnt;dis[1][0]=t1;dis[1][1]=p1;
k-=2;
while (k){
sta[++top]=k%2;
k/=2;
}
while (top){
mult(ans,ans,ans);
if (sta[top]) mult(ans,dis,ans);
top--;
}
mult(a,ans,a);
num=a[0][0];
(num+=mo)%=mo;
printf("%d\n",num);
}