hihocoder 1290 DP
阅读原文时间:2023年09月06日阅读:1

题目利用DP思想,dp[i][j][k]表示robot跑到ij列目前移动方向为k时,所需要的最小的flip。其中0 <= i <= N0 <= j <= Mk = right/down

dp[i][j][right] 可由dp[i][j-1][right]右移和dp[i-1][j][down]下移两种情况得到:

1. dp[i][j-1][right]右移一步,到dp[i][j][right],若maze[i][j] == 'b',则dp[i][j][right]=dp[i][j-1][right] +1;

2. dp[i-1][j][down]下移时,需要改变方向,先下移一步到第i行j列,此时方向是向下的,要变为向右,需考虑maze[i+1][j],若i+1==n(边界)或者maze[i+1][j] == 'b',则表示向下行不通,便直接改变方向向右;若第i+1行j列可以走的话,需将其变为'b',使其行不通,才能改变方向为向右。故可表示为以下公式:

dp[i][j][right] = min(dp[i][j-1][right], dp[i-1][j][down] + (i+1 < n && maze[i+1][j] != 'b')) + (maze[i][j] == 'b');

dp[i][j][down]同理如下;

dp[i][j][down] = min(dp[i-1][j][down], dp[i][j-1][right] + (j+1 < m && maze[i][j+1] != 'b')) + (maze[i][j] == 'b');

#include <iostream>
#include <vector>
#include <algorithm>
#include<map>
#include<vector>
#include<queue>
#include<string>
#include<set>
#include<cmath>
#include<cstdio>
#include<sstream>
#include<cstring>
//#pragma warning(disable:4996)
using namespace std;
#define MAXN 50001
#define INF INT_MAX
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define L(a) ((a)<<1)
#define R(a) (((a)<<1)+1)
int n, m;
int dp[105][105][2];
char a[105][105];
int cal() {
    //0表示right ,1 表示down
    dp[0][0][0] = (a[0][0] == 'b');
    dp[0][0][1] = dp[0][0][0] + (1 < m&&a[0][1] != 'b');
    for (int i = 1; i < n; ++i) {
        dp[i][0][1] = min(dp[i - 1][0][0] + (1 < m&&a[i - 1][1] != 'b'), dp[i - 1][0][1]) + (a[i][0] == 'b');
        dp[i][0][0] = dp[i][0][1] + (i + 1 < n&&a[i + 1][0] != 'b');
    }
    for (int i = 1; i < m; ++i) {
        dp[0][i][0] = min(dp[0][i - 1][0], dp[0][i - 1][1] + (1 < m&&a[1][i - 1] != 'b')) + (a[0][i] == 'b');
        dp[0][i][1] = dp[0][i][0] + (i + 1 < m&&a[0][i + 1] != 'b');
    }
    for (int i = 1; i < n; ++i) {
        for (int j = 1; j < m; ++j) {
            dp[i][j][0] = min(dp[i][j - 1][0], dp[i - 1][j][1] + (i + 1 < n && a[i + 1][j] != 'b')) + (a[i][j] == 'b');
            dp[i][j][1] = min(dp[i - 1][j][1], dp[i][j - 1][0] + (j + 1 < m && a[i][j + 1] != 'b')) + (a[i][j] == 'b');
        }
    }
    return min(dp[n - 1][m - 1][0], dp[n - 1][m - 1][1]);
}
int main()
{
    while (cin >> n >> m) {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                cin >> a[i][j];
            }
        }
        cout << cal() << endl;
    }
    return 0;
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章