UVa 825 Walking on the Safe Side (DP)

/**
*  dp题: 
*  状态转移方程都好写。 
*    这题关键是审题!! 花了我几小时去debug,结果是输出的时候错了,
*  不是没个case之后都要输出回车的, 只有相邻两个,诶。。。。
*/
 
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#define INF 0x7fffffff
#define MAXS 101
#define DEBUG 0
#define LL long long
using namespace std;
int md[MAXS][MAXS], dp[MAXS][MAXS];
int r, c;

void init() {
    for(int i = 0; i <= r; i ++) {
        for(int j = 0; j <= c; j ++) {
            md[i][j] = INF;
            dp[i][j] = -1;
        }
    }
    md[1][1] = 0;
    dp[1][1] = 1;
}

void dpf() {
    if(md[1][1] == -1) {
        return ;
    }
    for(int i = 1; i <= r; i ++) {
        for(int j = 1; j <= c; j ++) {
            if(md[i][j] == -1) continue;

            if(dp[i - 1][j] != -1) {
                md[i][j] = md[i - 1][j] + 1;
                dp[i][j] = dp[i - 1][j];
            }
            if(md[i][j - 1] + 1 < md[i][j] && dp[i][j - 1] != -1) {
                md[i][j] = md[i][j - 1] + 1;
                dp[i][j] = dp[i][j - 1];
            } else if(md[i][j - 1] + 1 == md[i][j] && dp[i][j - 1] != -1) {
                dp[i][j] += dp[i][j - 1];
            }
        }
    }
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T --) {
        char cur;
        int icur;
        scanf("%d%d", &r, &c);
        init();
        bool putted = false;
        for(int curR = 1; curR <= r; curR ++) {
            scanf("%d", &icur);
            cur = getchar();
            if(cur == '\n') continue;
            icur = 0;
            while(cur = getchar(), cur != '\n') {
                if(cur == ' ') {
                    if(putted == false)
                    md[curR][icur] = -1;
                    putted = true;
                    icur = 0;
                    continue;
                }
                putted = false;
                icur = icur * 10 + (cur - '0');
            }
            md[curR][icur] = -1;
        }
        dpf();
        if(dp[r][c] == -1) printf("0\n\n");
        else printf("%d\n", dp[r][c]);
        if(T) printf("\n");
    }
    return 0;
}

你可能感兴趣的:(UVa 825 Walking on the Safe Side (DP))