首页 > 代码库 > HDU4925-Apple Tree

HDU4925-Apple Tree

题意:n*m网格中种苹果,每个网格要么施肥,要么种一个苹果,每个种苹果的格子,如果它的上下左右有各自有施肥的话,每有一个,苹果数量*2,求怎么种使得苹果数量最多。


思路:交叉种植,即黑白染色法可得到最优解。注意特判当n=m=1时的情况。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAXN = 105;

int n, m;
int g[MAXN][MAXN];

int deal(int x, int y) {
    int sum = 1;
    if (g[x][y - 1] == 1)
        sum *= 2;
    if (g[x][y + 1] == 1)
        sum *= 2;
    if (g[x - 1][y] == 1)
        sum *= 2;
    if (g[x + 1][y] == 1)
        sum *= 2;
    return sum;
}

int main() {
    int cas;
    scanf("%d", &cas);
    while (cas--) {
        scanf("%d%d", &n, &m);         
        if (n == 1 && m == 1) {
            printf("1\n"); 
            continue; 
        }
        memset(g, 0, sizeof(g));
        int flag = 1;
        if (m % 2 == 1) {
            for (int i = 1; i <= n; i++) 
                for (int j = 1; j <= m; j++) {
                    g[i][j] = flag; 
                    flag = -flag; 
                } 
        }
        else {
            for (int i = 1; i <= n; i++) { 
                for (int j = 1; j <= m; j++) {
                    g[i][j] = flag; 
                    flag = -flag; 
                }
                flag = -flag;
            }
        }

        long long ans = 0;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++) 
                if (g[i][j] == -1)
                    ans += deal(i, j); 

        printf("%lld\n", ans);   
    }
    return 0;
}