位元運算要注意 (對於HDOJ 1547的思考)

來源:互聯網
上載者:User

今天真坑爹,一個位操作x&1 == 0導致了一種奇妙的錯誤,也讓我反思頗深,乍一看這個式子我們估計大部分人都理解成了(x&1) == 0

其實不然,因為&比==的優先順序更低,所以應該是這樣運算的x&(1 == 0)

坑吧

搞得我HDOJ 1547wa了一下午,頭痛欲裂

#include<stdio.h>#include<string.h>#include<stdlib.h>char map[111][111];int h, w;int x, y;int gone[111][111];int check(int x, int y, char c){if(x < 1 || x > h || y < 1)return 0;if((x & 1) == 0 && y > w - 1)  //就是這裡錯誤了return 0;if((x & 1) == 1 && y > w)return 0;if(map[x][y] != c)return 0;if(gone[x][y])return 0;return 1;}int find(int x, int y){int result = 0;if(x == 35 && y == 1)printf("");gone[x][y] = 1;if(check(x + 1, y, map[x][y])){result += find(x + 1, y);}if(check(x - 1, y, map[x][y]))result += find(x - 1, y);if((x % 2 == 1) && check(x + 1, y - 1, map[x][y])){result += find(x + 1, y - 1);}if((x % 2 == 1) && check(x - 1, y - 1, map[x][y]))result += find(x - 1, y - 1);if(x % 2 == 0 && check(x + 1, y + 1, map[x][y])){result += find(x + 1, y + 1);}if(x % 2 == 0 && check(x - 1, y + 1, map[x][y]))result += find(x - 1, y + 1);if(check(x, y - 1, map[x][y]))result += find(x, y - 1);if(check(x, y + 1, map[x][y]))result += find(x, y + 1);return result + 1;}int check1(int x, int y){if(x < 1 || x > h || y < 1)return 0;if((x & 1) == 0 && y > w - 1)return 0;if((x & 1) == 1 && y > w)return 0;if(gone[x][y])return 0;if(map[x][y] == 'E')return 0;return 1;}int go(int x, int y){if(x == 35 && y == 1)printf("");gone[x][y] = 1;if(check1(x + 1, y)){go(x + 1, y);}if(check1(x - 1, y))go(x - 1, y);if((x % 2 == 1) && check1(x + 1, y - 1)){go(x + 1, y - 1);}if((x % 2 == 1) && check1(x - 1, y - 1))go(x - 1, y - 1);if(x % 2 == 0 && check1(x + 1, y + 1)){go(x + 1, y + 1);}if(x % 2 == 0 && check1(x - 1, y + 1))go(x - 1, y + 1);if(check1(x, y - 1))go(x, y - 1);if(check1(x, y + 1))go(x, y + 1);return 0;}int main(){int i, result, j;while(scanf("%d%d%d%d", &h, &w, &x, &y) != EOF){for(i = 1; i <= h; i ++){scanf("%s", map[i] + 1);//for(j = 1; j <= w; j ++)//{//map[i][j] = rand() % 3 + 'a';//if(rand() % 26 == 0)//map[i][j] = 'E';//}}result = 0;memset(gone, 0, sizeof(gone));if((result = find(x, y)) >= 3){for(j = 1; j <= w; j ++){if(!gone[1][j] && map[1][j] != 'E'){go(1, j);}}for(i = 1; i <= h; i ++)for(j = 1; j <= w - (i % 2 == 0 ? 1 : 0); j ++){if(!gone[i][j] && map[i][j] != 'E')result ++;}printf("%d\n", result);}elseprintf("0\n");}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.