• HackerRank


    This is my 1st 3D DP problem, and it should be an educational one. But, still tricky to me.
    Here is a good article: http://www.cnblogs.com/sunshineatnoon/p/3919423.html, and I simply re-code it in C++, for learning :)

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <map>
    #include <set>
    #include <unordered_set>
    #include <string>
    #include <climits>
    #include <iostream>
    #include <algorithm>
    #include <unordered_map>
    #include <unordered_set>
    using namespace std;
    
    int CalcMin(int i, int j, int k,
        vector<vector<vector<int>>> &dp,
        vector<string> &map)
    {
        int min_mv = INT_MAX - 1;
        int n = map.size();
        int m = map[0].size();
    
        if (i - 1 >= 0)
        {
            int newMv = dp[i - 1][j][k - 1] + (map[i - 1][j] == 'D' ? 0 : 1);
            min_mv = std::min(min_mv, newMv);
        }
        if (i + 1 < n)
        {
            int newMv = dp[i + 1][j][k - 1] + (map[i + 1][j] == 'U' ? 0 : 1);
            min_mv = std::min(min_mv, newMv);
        }
        if (j - 1 >= 0)
        {
            int newMv = dp[i][j - 1][k - 1] + (map[i][j - 1] == 'R' ? 0 : 1);
            min_mv = std::min(min_mv, newMv);
        }
        if (j + 1 < m)
        {
            int newMv = dp[i][j + 1][k - 1] + (map[i][j + 1] == 'L' ? 0 : 1);
            min_mv = std::min(min_mv, newMv);
        }
        return min_mv;
    }
    
    int main()
    {
        int n, m, K;
        cin >> n >> m >> K;
    
        int sx, sy;
    
        vector<string> map;
        for (int i = 0; i < n; i++)
        {
            char buf[60] = { 0 };
            scanf("%s", buf);
            string s(buf);
            size_t inx;
            if ((inx = s.find('*')) != string::npos)
            {
                sx = i;
                sy = inx;
            }
            map.push_back(s);
        }
    
        //
        vector<vector<vector<int>>> dp(n, vector<vector<int>>(m, vector<int>(K + 1)));
        for (int k = 0; k <= K; k++)
        for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
        {
            if (k == 0)    // INIT
            {
                dp[i][j][k] = ((i + j) == 0) ? 0 : INT_MAX - 1;
            }
            else
            {
                dp[i][j][k] = CalcMin(i, j, k, dp, map);
            }
        }
    
        //    Get Min
        int ret = INT_MAX - 1;
        for (int k = 0; k <= K; k++)
            ret = std::min(ret, dp[sx][sy][k]);
    
        cout << (ret == (INT_MAX - 1) ? -1 : ret) << endl;
        return 0;
    }
  • 相关阅读:
    【NOIP模拟赛】正方形大阵
    【优化王牌】二分查找
    【Ah20160703】咏叹 By C_SUNSHINE
    【NOIP模拟赛】lover——心上人
    【小奇模拟赛】小奇挖矿2
    【NOIP模拟赛】工资
    关于博客装修的说明
    【快速处理】分块算法
    【集训】 考试笔记
    【HDNOIP】HD201404最短路径
  • 原文地址:https://www.cnblogs.com/tonix/p/4506132.html
Copyright © 2020-2023  润新知