……每一位独立,直接朴素dp即可。
(可以类似插头dp一样逐格转移优化掉一个
2
n
2^n
2n但是懒的写了)
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define lint long long
#define ull unsigned lint
#define gc getchar()
#define N 7
#define M 10010
#define S 35
#define INF (LLONG_MAX/10)
#define debug(x) cerr<<#x<<"="<<x
#define sp <<" "
#define ln <<endl
using namespace std;
typedef pair<int,int> pii;
typedef set<int>::iterator sit;
inline int inn()
{
int x,ch;while((ch=gc)<'0'||ch>'9');
x=ch^'0';while((ch=gc)>='0'&&ch<='9')
x=(x<<1)+(x<<3)+(ch^'0');return x;
}
int a[N][M],b[N][M],r[N][M],d[N][M],v[N][M];
int trs[M][S],init_val[M][S],val[M][S];lint dp[M][S];
inline int getv(int x,int p) { return (x>>(p-1))&1; }
inline lint solve(int m,int all)
{
rep(j,1,m) rep(s,0,all) dp[j][s]=INF;
rep(s,0,all) dp[1][s]=0;
rep(j,1,m) rep(s,0,all)
{
dp[j][s]+=val[j][s];if(j==m) continue;
rep(t,0,all) dp[j+1][t]=min(dp[j+1][t],dp[j][s]+trs[j][s^t]);
}
// rep(j,1,m) rep(s,0,all) debug(j)sp,debug(s)sp,debug(dp[j][s])ln,(s==all?cerr ln,0:0);
lint ans=INF;rep(s,0,all) ans=min(ans,dp[m][s]);return ans;
}
int main()
{
int n=inn(),m=inn(),all=(1<<n)-1,mxa=0;
rep(i,1,n) rep(j,1,m) a[i][j]=inn(),mxa=max(mxa,a[i][j]);
rep(j,1,m) a[n+1][j]=a[1][j];
rep(i,1,n) rep(j,1,m) b[i][j]=inn();
rep(i,1,n) rep(j,1,m-1) r[i][j]=inn();
rep(i,1,n) rep(j,1,m) d[i][j]=inn();
rep(j,1,m-1) rep(s,0,all) rep(i,1,n) if(getv(s,i)) trs[j][s]+=r[i][j];
// rep(j,1,m-1) rep(s,0,all) debug(j)sp,debug(s)sp,debug(trs[j][s])ln,(s==all?cerr ln,0:0);
rep(j,1,m) rep(s,0,all) rep(i,1,n)
if(getv(s,i)!=getv(s,i%n+1)) init_val[j][s]+=d[i][j];
// rep(j,1,m) rep(s,0,all) debug(j)sp,debug(s)sp,debug(init_val[j][s])ln,(s==all?cerr ln,0:0);
int k=0;while(mxa) mxa>>=1,k++;lint ans=0;
rep(t,1,k)
{
rep(i,1,n) rep(j,1,m) v[i][j]=getv(a[i][j],t);
rep(j,1,m) rep(s,0,all) val[j][s]=init_val[j][s];
// rep(i,1,n) rep(j,1,m) cerr<<v[i][j]sp,(j==m?cerr ln,0:0);
rep(j,1,m) rep(s,0,all) rep(i,1,n)
val[j][s]+=(v[i][j]^getv(s,i))*b[i][j];
// rep(j,1,m) rep(s,0,all) debug(j)sp,debug(s)sp,debug(val[j][s]-init_val[j][s])ln,(s==all?cerr ln,0:0);
// cerr<<t-1 sp <<solve(m,all) ln;
ans+=solve(m,all)*(1<<(t-1));
}
return !printf("%lld\n",ans);
}