use sentinel to avoid boudary testing,
use swap trick to avoid extra copy.
original version
#include <cstdio>
#include <algorithm>
int main() {
//freopen("input.txt","r",stdin);
const int MAXSIZE=22, dimSize=20;
int bacnums1[MAXSIZE][MAXSIZE]={0},bacnums2[MAXSIZE][MAXSIZE]={0}, (*now)[MAXSIZE]=bacnums1, (*next)[MAXSIZE]=bacnums2, dna[16];
int ncase, nday, i,j,tmp;
if(scanf("%d",&ncase)!=1 || ncase<=0) return -1;
while(ncase--) {
scanf("%d",&nday);
for(i=0;i<16;++i) scanf("%d",&dna[i]);
for(i=1;i<=dimSize;++i)
for(j=1;j<=dimSize;++j)
scanf("%d",&now[i][j]);
while(nday-->0) {
for(i=1;i<=dimSize;++i)
for(j=1;j<=dimSize;++j) {
tmp=now[i][j]+now[i-1][j]+now[i+1][j]+now[i][j-1]+now[i][j+1];
next[i][j]=now[i][j]+dna[tmp];
if(next[i][j]<0) { next[i][j]=0; }
else if(next[i][j]>3) { next[i][j]=3; }
}
std::swap(now,next);
}
for(i=1;i<=dimSize;++i) {
for(j=1;j<=dimSize;++j)
switch(now[i][j]) {
case 0: putchar('.'); break;
case 1: putchar('!'); break;
case 2: putchar('X'); break;
case 3: putchar('#'); break;
default: break;
}
putchar('
');
}
if(ncase) putchar('
');
}
return 0;
}
version 2, fgets + parsing, write to a buffer then output,
since the lines are quite short, there is no performance improvement.
#include <cstdio>
#include <algorithm>
int main() {
//freopen("input.txt","r",stdin);
const int MAXSIZE=22, dimSize=20, lineMaxSize=500;
int bacnums1[MAXSIZE][MAXSIZE]={0},bacnums2[MAXSIZE][MAXSIZE]={0}, (*now)[MAXSIZE]=bacnums1, (*next)[MAXSIZE]=bacnums2, dna[16];
char line[lineMaxSize],output[lineMaxSize], *pc;
int ncase, nday, i,j,tmp, *p, *pend;
if(scanf("%d",&ncase)!=1 || ncase<=0) return -1;
while(ncase--) {
scanf("%d
",&nday);
pc=fgets(line,lineMaxSize,stdin);
for(p=dna,pend=dna+16;p!=pend;++p) {
for(;*pc==' ';++pc) ;
if(*pc=='-') { tmp='0'-*++pc; }
else { tmp=*pc-'0'; }
++pc; *p=tmp;
}
for(i=1;i<=dimSize;++i) {
pc=fgets(line,lineMaxSize,stdin);
for(p=&now[i][1],pend=p+dimSize;p!=pend;++p) {
for(;*pc==' ';++pc) ;
*p=*pc++ -'0';
}
}
while(nday-->0) {
for(i=1;i<=dimSize;++i)
for(j=1;j<=dimSize;++j) {
tmp=now[i][j]+now[i-1][j]+now[i+1][j]+now[i][j-1]+now[i][j+1];
next[i][j]=now[i][j]+dna[tmp];
if(next[i][j]<0) { next[i][j]=0; }
else if(next[i][j]>3) { next[i][j]=3; }
}
std::swap(now,next);
}
for(pc=output, i=1;i<=dimSize;++i) {
for(j=1;j<=dimSize;++j)
switch(now[i][j]) {
case 0: *pc++='.'; break;
case 1: *pc++='!'; break;
case 2: *pc++='X'; break;
case 3: *pc++='#'; break;
default: break;
}
*pc++='
';
}
if(ncase) *pc=0; else *(pc-1)=0;
puts(output);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。// p.s. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.