演算法競賽入門經典(第二版) 習題3-5 謎題(Puzzle) UVa227 Finals1993
阿新 • • 發佈:2019-01-02
Page 57
Description
一個5*5的網格中恰好有一個格子是空的,其他格子各有一個字母,四條指令A,B,L,R分別表示將空格上、下、左、右移動。輸入初始網格(以Z結束)和一串指令(以0結束),輸出執行操作後的網格。越界則輸出“This puzzle has no final configuration.”。
TRGSJ
XDOKI
M VLN
WPABE
UQHCF
ARRBBL0
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAA
LLLL0
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAAAABBRRRLL0
Z
Puzzle #1: T R G S J X O K L I M D V B N W P A E U Q H C F Puzzle #2: A B C D F G H I E K L M N J P Q R S O T U V W X Puzzle #3: This puzzle has no final configuration.
Note
不得不承認final的題就是不一樣Orz,就算不難,半小時寫好框架卻花了一下午時間找bug,修改了N次後還是WA,我想到有可能是PE只是評測系統返回WA。
Separate output from different puzzle records by one blank line.
這句話就是罪魁禍首,其實它的意思是將輸出和puzzle用一行隔開,然而我以為應該是這樣輸出的:
尼瑪以前不都是這麼輸出的麼!!Too young too simple...(PS這種輸出格式實在找不到一種判斷方法讓最後不輸出空行)
後來想了想,換了一種輸出格式:
這樣應該對了吧?又WA了!其實想想也應該是錯的,因為它重定向後其實等於這樣輸出:
看到沒?第一個輸出前面不應該有空行。所以只要第一個不輸出空行就可以AC啦。BTW,這樣的輸出格式有個好處,就是解決了這種輸入格式怎麼防止最後一個輸出空行的問題~不愧是finals題 Orz
這題主要還是細節問題,比如如果puzzle的空格在一行中的最後,那麼輸出其實輸到第4個就不用輸了,所以第5個元素a[i][4]相當於'\0',此時要把它換成空格才好處理。另外由於輸入中有空格,所以要用gets()。
執行結果:#include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> using namespace std; #define max 105 char s[max],ss[max]; char a[10][10],t; int main(){ //freopen("in.txt","r",stdin); int i,j,l,m,n,cas=0; loop: while(gets(a[0])){ //while(gets()) if(a[0][0]=='Z') break; for(i=1;i<5;i++) gets(a[i]); for(i=0;i<5;i++){ if(a[i][4]==0) {a[i][4]=' ';m=i;n=4;break;} for(j=0;j<5;j++) if(a[i][j]==' ') {m=i;n=j;break;} } gets(s); l=strlen(s); while(s[l-1]!='0'){ //保證指令可以分行輸入 gets(ss); strcat(s,ss); l=strlen(s); } if(cas!=0) putchar(10); i=0; while(s[i]!='0'){ switch (s[i]){ case 'A':{ if(m-1>=0) {t=a[m][n];a[m][n]=a[m-1][n];a[m-1][n]=t;m--;} else {printf("Puzzle #%d:\nThis puzzle has no final configuration.\n",++cas);goto loop;} break; } case 'B':{ if(m+1<5) {t=a[m][n];a[m][n]=a[m+1][n];a[m+1][n]=t;m++;} else {printf("Puzzle #%d:\nThis puzzle has no final configuration.\n",++cas);goto loop;} break; } case 'L':{ if(n-1>=0) {t=a[m][n];a[m][n]=a[m][n-1];a[m][n-1]=t;n--;} else {printf("Puzzle #%d:\nThis puzzle has no final configuration.\n",++cas);goto loop;} break; } case 'R':{ if(n+1<5) {t=a[m][n];a[m][n]=a[m][n+1];a[m][n+1]=t;n++;} else {printf("Puzzle #%d:\nThis puzzle has no final configuration.\n",++cas);goto loop;} break; } } i++; } printf("Puzzle #%d:\n",++cas); for(i=0; i<5; i++) printf("%c %c %c %c %c\n",a[i][0],a[i][1],a[i][2],a[i][3],a[i][4]); } return 0; }