HDU4925 Apple Tree(位运算相关知识)

来源:互联网 发布:矩阵扰动理论 编辑:程序博客网 时间:2024/05/29 02:47

I’ve bought an orchard and decide to plant some apple trees on it. The orchard seems like an N * M two-dimensional map. In each grid, I can either plant an apple tree to get one apple or fertilize the soil to speed up its neighbors’ production. When a grid is fertilized, the grid itself doesn’t produce apples but the number of apples of its four neighbor trees will double (if it exists). For example, an apple tree locates on (x, y), and (x - 1, y), (x, y - 1) are fertilized while (x + 1, y), (x, y + 1) are not, then I can get four apples from (x, y). Now, I am wondering how many apples I can get at most in the whole orchard?
Input
The input contains multiple test cases. The number of test cases T (T<=100) occurs in the first line of input.
For each test case, two integers N, M (1<=N, M<=100) are given in a line, which denote the size of the map.
Output
For each test case, you should output the maximum number of apples I can obtain.
Sample Input
2
2 2
3 3
Sample Output
8
32

#include<stdio.h>#include<string.h>int mp[110][110];int main(){    int n,a,sum,k,m,i,j,t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        memset(mp,0,sizeof(mp));        for(i=1;i<=n;i++)        {            for(j=1;j<=m;j++)            {                if((i+j)&1) mp[i][j]=1;//如果i+j是奇数 也可写成(i+j)%2!=0            }        }        sum=0;        for(i=1;i<=n;i++)        {            for(j=1;j<=m;j++)            {                if(mp[i][j]==0)                {                    k=1;                    if(mp[i-1][j]) k*=2;                    if(mp[i][j-1]) k*=2;                    if(mp[i][j+1]) k*=2;                    if(mp[i+1][j]) k*=2;                    sum+=k;                }            }        }        printf("%d\n",sum);    }    return 0;}

按位与:

if(i&1==1) 表示 如果是 奇数 则。。。
i&1 – 按位与运算,取 2进制整数 i 的最低位,如果最低位是1 则得1,如果最低位是0 则得0。 奇数 i 的最低位 是1,偶数i 的最低位 是0。
i 2进制 &1
0 0000 0000 &1 得0 偶数
1 0000 0001 &1 得1 奇数
2 0000 0010 &1 得0 偶数
3 0000 0011 &1 得1 奇数
4 0000 0100 &1 得0 偶数
if((i&1)==1){} 和 if(i& (1==1) ){} 的结果 一样,表示 如果是 奇数 则执行 {}. 因为 1==1 得 真,真就是 1,然后 i & 1, i奇数得1,i偶数得0。所以 i奇数 执行 {}.

http://baike.baidu.com/link?url=J5SvmHLca6qF-Y7YrCHBvBH9sxcWRaLuEXFqC8I_9BdLBUpj4KqFiXnsEnad7FWDeGI6HPZAXpc0OJxIcxULAx1p1BQlhRhDyAl0Q-g0KrjDKVIlcxNG6B2idKHRCRZc

原创粉丝点击