【算法设计与数据结构】动态规划入门——URAL 1119 Metro

Many of SKB Kontur programmers like to get to work by Metro because the main office is situated quite close the station Uralmash. So, since a sedentary life requires active exercises off-duty, many of the staff — Nikifor among them — walk from their homes to Metro stations on foot.

Problem illustration

Nikifor lives in a part of our city where streets form a grid of residential quarters. All the quarters are squares with side 100 meters. A Metro entrance is situated at one of the crossroads. Nikifor starts his way from another crossroad which is south and west of the Metro entrance. Naturally, Nikifor, starting from his home, walks along the streets leading either to the north or to the east. On his way he may cross some quarters diagonally from their south-western corners to the north-eastern ones. Thus, some of the routes are shorter than others. Nikifor wonders, how long is the shortest route.

You are to write a program that will calculate the length of the shortest route from the south-western corner of the grid to the north-eastern one.

Input

There are two integers in the first line: N and M (0 < NM ≤ 1000) — west-east and south-north sizes of the grid. Nikifor starts his way from a crossroad which is situated south-west of the quarter with coordinates (1, 1). A Metro station is situated north-east of the quarter with coordinates ( NM). The second input line contains a number K (0 ≤ K ≤ 100) which is a number of quarters that can be crossed diagonally. Then K lines with pairs of numbers separated with a space follow — these are the coordinates of those quarters.

Output

Your program is to output a length of the shortest route from Nikifor's home to the Metro station in meters, rounded to the integer amount of meters.

Example

input output
3 2
3
1 1
3 2
1 2
383

题解:简单dp,由已知状态推位置状态,考虑边界状态,特判对角线状态。

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int vis[1010][1010];
double dp[1010][1010];
int main()
{
    int n,m,k;
    cin>>n>>m>>k;
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=k;i++)
    {
        int u,v;
        cin>>u>>v;
        vis[u][v]=1;    //对角线标记
    }
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++) //初始化边界条件
        dp[i][0]=i*100;
    for(int j=1;j<=m;j++)
        dp[0][j]=j*100;
    for(int i=1;i<=n;i++)   //由已知状态推未知状态
    {
        for(int j=1;j<=m;j++)
        {
            dp[i][j]=min(dp[i-1][j]+100,dp[i][j-1]+100);
            if(vis[i][j])
            {
                dp[i][j]=min(dp[i][j],dp[i-1][j-1]+sqrt(20000.0)); //注意这里一定是sqrt(20000.0)不然会产生误差
            }
        }
    }
    cout<<(int)(dp[n][m]+0.5)<<endl;//四舍五入
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87996873