#include using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) FOR(i,0,n) #define pb emplace_back typedef long long ll; typedef pair pint; unsigned long xor128(){ static unsigned long x=123456789,y=362436069,z=521288629,w=88675123; unsigned long t=(x^(x<<11)); x=y;y=z;z=w; return (w=(w^(w>>19))^(t^(t>>8))); } double timeLimit=0.91; const int64_t CYCLES_PER_SEC=2800000000; struct Timer { int64_t start; Timer() { reset(); } void reset() { start = getCycle(); } void plus(double a) { start -= (a * CYCLES_PER_SEC); } inline double get() { return (double)(getCycle() - start) / CYCLES_PER_SEC; } inline int64_t getCycle() { uint32_t low, high; __asm__ volatile ("rdtsc" : "=a" (low), "=d" (high)); return ((int64_t)low) | ((int64_t)high << 32); } }; int n,k; int L[501]; string s[60]; bool g[60][60],g2[60][60]; vector > ans(500); int lx,rx,ly,ry; int best,sub; int sumx[61][61],sumy[61][61]; pair calc(int length){ pair ret; pint best={-1000100010,0}; pint score; int slide=1; rep(i,n)rep(j,n-length+1)if(g[i][j]|g[i][j+length-1]){ score={0,0}; slide=1; while(j-slide>=0&&g[i][j-slide]^g[i][j]&&slide<3) ++score.second,++slide; slide=length; while(j+slide0&&g[i][j+k-1]^g[i][j+k]) --score.second; if(i-1>=0&&g[i][j+k]^g[i-1][j+k]) ++score.second; if(i+1=0&&g[j-slide][i]^g[j][i]&&slide<3) ++score.second,++slide; slide=length; while(j+slide0&&g[j+k-1][i]^g[j+k][i]) --score.second; if(i-1>=0&&g[j+k][i]^g[j+k][i-1]) ++score.second; if(i+1 calc2(int length){ pair ret; int best=-1000100010; int slide=1; rep(i,n)rep(j,n){ sumx[i][j+1]=sumx[i][j]+g[i][j]; sumy[i+1][j]=sumy[i][j]+g[i][j]; } rep(i,n-length+1)rep(j,n-length+1)if(g[i][j]){ int score=sumx[i][j+length]-sumx[i][j]; if(best>n>>k; rep(i,k) cin>>L[i]; //sort(L,L+k,greater()); rep(i,n) cin>>s[i]; rep(i,n)rep(j,n) g[i][j]|=s[i][j]-'0'; rep(i,k) ans[i]=calc(L[i]); best=get_score(); memcpy(g2,g,sizeof(g)); int id,num=4; vector cnd(num); vector >tmp(num); double t; while(1){ t=timer.get(); if(t>timeLimit) break; if(t>timeLimit-0.2) num=3; sub=0; rep(l,num){ while(id=xor128()%k,count(cnd.begin(),cnd.begin()+l,pint(L[id],id))||L[id]==1); cnd[l]={L[id],id}; ly=ans[id].first.first,lx=ans[id].first.second,ry=ans[id].second.first,rx=ans[id].second.second; if(ly==ry)FOR(j,lx,rx+1) g[ly-1][j-1]^=1,sub+=g[ly-1][j-1]?-1:1; else FOR(i,ly,ry+1) g[i-1][lx-1]^=1,sub+=g[i-1][lx-1]?-1:1; } rep(i,num){ tmp[i]=calc2(cnd[i].first); } if(sub>=0){ best+=sub; memcpy(g2,g,sizeof(g)); rep(i,num)ans[cnd[i].second]=tmp[i]; } else memcpy(g,g2,sizeof(g2)); } //cerr<