poj-3230 Travel

One traveler travels among cities. He has to pay for this while he can get some incomes.

Now there are n cities, and the traveler has m days for traveling. Everyday he may go to another city or stay there and pay some money. When he come to a city ,he can get some money. Even when he stays in the city, he can also get the next day's income. All the incomes may change everyday. The traveler always starts from city 1.

Now is your turn to find the best way for traveling to maximize the total income.

Input

There are multiple cases.

The first line of one case is two positive integers, n and m .n is the number of cities, and m is the number of traveling days. There follows n lines, one line n integers. The j integer in the i line is the expense of traveling from city i to city j. If i equals to j it means the expense of staying in the city.

After an empty line there are m lines, one line has n integers. The j integer in the i line means the income from city j in the i day.

The input is finished with two zeros.
n,m<100.

Output
You must print one line for each case. It is the max income.
Sample Input
3 3
3 1 2
2 3 1
1 3 2

2 4 3
4 3 2
3 4 2

0 0
Sample Output
8
Hint
In the Sample, the traveler can first go to city 2, then city 1, and finish his travel in city 1. The total income is:
-1+4-2+4-1+4=8;

OJ-ID:
poj-3230

author:
Caution_X

date of submission:
20191019

tags:
dp

description modelling:
某人去旅行一趟,输入包含从城市i->j的花费cost[i][j]和第i天待在城市j可以得到的钱w[i][j],求m天后的最大钱数

major steps to solve it:
dp[i][j]:=第i天待在第j个成=城市得到的最大金钱
dp[i][j]=max(dp[i][j],dp[i-1][k]-cost[k][j]+w[i][j]);

AC code:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int dp[105][105],w[105][105],cost[105][105];
int main()
{
    //freopen("input.txt","r",stdin);
    int n,m;
    while(~scanf("%d%d",&n,&m)&&n&&m) {
        memset(dp,-1,sizeof(dp));
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=n;j++) {
                scanf("%d",&cost[i][j]);
            }
        }
        for(int i=1;i<=m;i++) {
            for(int j=1;j<=n;j++) {
                scanf("%d",&w[i][j]);
            }
        }
        dp[0][1]=0;
        for(int i=1;i<=n;i++) dp[1][i]= -cost[1][i]+w[1][i];
        for(int i=2;i<=m;i++) {
            for(int j=1;j<=n;j++) {
                for(int k=1;k<=n;k++) {
                    dp[i][j]=max(dp[i][j],dp[i-1][k]-cost[k][j]+w[i][j]);
                }
            }
        }
        int ans=-2000000000;
        for(int i=1;i<=n;i++) {
            ans=max(ans,dp[m][i]);
        }
        printf("%d\n",ans);
    }
}

 

posted on 2019-10-21 21:52  Caution_X  阅读(128)  评论(0编辑  收藏  举报

导航