Flip Game
Time Limit: 15000/5000 MS (Java/Others) Memory Limit:
65535/32768 K (Java/Others)
Problem DescriptionFlip game is played on a square N*N field with two-sided pieces placed on each of its N^2 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. The rows are numbered with integers from
1 to N upside down; the columns are numbered with integers from 1 to N from the left to the right. Sequences of commands (xi, yi) are given from input, which means that both pieces in row xi and pieces in column yi will
be flipped (Note that piece (xi, yi) will be flipped twice here). Can you tell me how many white pieces after sequences of commands?
Consider the following 4*4 field as an example:
bwww
wbww
wwbw
wwwb
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up.
Two commands are given in order: (1, 1), (4, 4). Then we can get the final 4*4 field as follows:
bbbw
bbwb
bwbb
wbbb
So the answer is 4 as there are 4 white pieces in the final field. InputThe first line contains a positive integer T, indicating the number of test cases (1 <= T <= 20).
For each case, the first line contains a positive integer N, indicating the size of field; The following N lines contain N characters each which represent the initial field. The following line contain an integer Q, indicating the number of commands; each of
the following Q lines contains two integer (xi, yi), represent a command (1 <= N <= 1000, 0 <= Q <= 100000, 1 <= xi, yi <= N). OutputFor each case, please print the case number (beginning with 1) and the number of white pieces after sequences of commands.
Sample Input
24bwwwwbwwwwbwwwwb21 14 44wwwwwwwwwwwwwwww11 1
Sample Output
Case #1: 4Case #2: 10
思路:
第一步,判斷field中有哪些行和列需要進行反轉,將這些行和列儲存到數組中。(使用了異或操作),對一行(列)改變偶數次等於沒改變;改變奇數次,相當於改變了一次(反轉)。
第二步,通過對行列的改變次數,確定field中的每一位是否需要改變(使用異或操作),行列交叉處改變2次,相當於沒有發生改變。
第三步,計算得到若反轉之後,共有多少個'w'。
代碼如下:
#include <stdio.h>#include <string.h>//一個N*N的方格,用來存放'b' or 'w'unsigned char field[1001][1001]; //一個N*N的方格,用來標記對應的field數組.若flag[i][j]為1,則要反轉,//即將field[i][j]中的字元由'b'改為'w'或者'w'改為'b';若flag[i][j]為0,//則無需改變.unsigned char flag[1001][1001]; int main(){int i,j,n,num,count=0,testcase,k,q,x,y;//col數組用來記錄field的列是否需要變化;row數組用來記錄field的行是否需要變化unsigned char col[1001],row[1001];scanf("%d",&testcase);while(testcase--){memset(flag,0,sizeof(flag));memset(col,0,sizeof(col));memset(row,0,sizeof(row));num = 0;count++;scanf("%d",&n);for(i=0;i<n;i++)scanf("%s",field[i]);scanf("%d",&q);//產生row和col數組的結果for(i=0;i<q;i++){scanf("%d %d",&x,&y);x = x-1;y = y-1;row[x] = row[x]^1;col[y] = col[y]^1;}//對flag數組進行操作,得到最終形成的0 1矩陣for(i=0;i<n;i++){for(k=0;k<n;k++)flag[i][k] = flag[i][k]^row[i];for(k=0;k<n;k++)flag[k][i] = flag[k][i]^col[i];}//根據flag數組,結合field數組,求得最終的'w'個數for(i=0;i<n;i++)for(j=0;j<n;j++){if((field[i][j] == 'w' && flag[i][j] == 0)||(field[i][j] == 'b' && flag[i][j] == 1))num++;}printf("Case #%d: %d\n",count,num);}return 0;}