1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include<bits/stdc++.h> #define fo(i,a,b) for(int i=a;i<=b;i++) using namespace std;
typedef long long LL;
const int maxn=20, maxN=262150; const int inf=2139062143;
int n,N,AA[maxn],v[maxn][4],v0[maxn],M[maxn],f[maxn][maxN],er[maxn]; bool G[maxn][maxn],A[maxn][maxn];
void ReadBit(bool &data) { char ch=getchar(); while (ch!='0' && ch!='1') ch=getchar(); data=(ch=='1'); }
inline void Min(int &a,const int &b) {a=(a<b) ?a :b ;}
int T; int main() { er[0]=1; fo(i,1,18) er[i]=er[i-1]<<1; scanf("%d",&T); while (T--) { scanf("%d",&n); N=(1<<n)-1; fo(i,1,n) { v0[i]=0; fo(j,1,n) { ReadBit(G[i][j]); if (G[i][j]) v[i][++v0[i]]=j; } } fo(i,1,n) { AA[i]=0; fo(j,1,n) { ReadBit(A[i][j]); AA[i]|=A[i][j]<<(j-1); } } fo(i,1,n) scanf("%d",&M[i]); memset(f,127,sizeof(f)); f[0][0]=0; fo(i,0,n-1) fo(s,0,N) if (f[i][s]<inf) { int nowL=s&(er[i]-1), nowR=s^nowL, nxt=i+1; bool alrdy=nowR&er[i]; int cho=s|er[i]; if (alrdy) Min(f[i+1][s^er[i]],f[i][s]); if (AA[nxt]&nowL || v0[nxt]==0) continue; if (alrdy || v[nxt][1]==nxt) Min(f[i+1][cho|er[v[nxt][1]-1]],f[i][s]+M[nxt]); if (v0[nxt]>1) { if (alrdy || v[nxt][2]==nxt) Min(f[i+1][cho|er[v[nxt][2]-1]],f[i][s]+M[nxt]); if (alrdy || v[nxt][1]==nxt || v[nxt][2]==nxt) Min(f[i+1][cho|er[v[nxt][1]-1]|er[v[nxt][2]-1]],f[i][s]+M[nxt]*M[nxt]); } if (v0[nxt]>2) { if (alrdy || v[nxt][3]==nxt) Min(f[i+1][cho|er[v[nxt][3]-1]],f[i][s]+M[nxt]); if (alrdy || v[nxt][1]==nxt || v[nxt][3]==nxt) Min(f[i+1][cho|er[v[nxt][1]-1]|er[v[nxt][3]-1]],f[i][s]+M[nxt]*M[nxt]); if (alrdy || v[nxt][2]==nxt || v[nxt][3]==nxt) Min(f[i+1][cho|er[v[nxt][2]-1]|er[v[nxt][3]-1]],f[i][s]+M[nxt]*M[nxt]); if (alrdy || v[nxt][1]==nxt || v[nxt][2]==nxt || v[nxt][3]==nxt) Min(f[i+1][cho|er[v[nxt][1]-1]|er[v[nxt][2]-1]|er[v[nxt][3]-1]],f[i][s]+M[nxt]*M[nxt]*M[nxt]); } } int ans=inf; fo(s,0,N) Min(ans,f[n][s]); printf("%d\n",(ans==inf) ?-1 :ans); } }
|