DP : Travel

本文探讨了一位旅行者如何在多个城市间旅行以最大化总收入的问题,通过每日选择前往另一城市或留在当前城市,同时考虑旅行费用和每日收入的变化。
Travel Time Limit:1000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64u

Description

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;


#include <cstdio>
#include <cstring>
#include <cstdio>
#include <iostream>

using namespace std;

int c[110][110], v[110][110];
int f[110][110]; //第i天在j城时的最大收入

int main(){
    int n, m;
    int i, j, k;
    while(cin >> n >> m){
        if(n == 0 && m == 0)
        break;
        for(i = 1; i <= n; i ++)
        for(j = 1; j <= n; j ++){
            scanf("%d", &c[i][j]);  //i城到j城花费
        }
        for(i = 1; i <= m; i ++)
        for(j = 1; j <= n; j ++){
            scanf("%d", &v[i][j]);  //j城第i天收入
        }
        memset(f, -10, sizeof(f));
        f[0][1] = 0;
        for(i = 1; i <= m; i ++){
            for(j = 1; j <= n; j ++){
                for(k = 1; k <= n; k ++){
                    f[i][j] = max(f[i][j], f[i-1][k] + v[i][j] - c[k][j]);
                }
            }
        }
        int max = -9999999;
        for(i = 1; i <= n; i ++){
            if(max < f[m][i])
                max = f[m][i];
        }
        cout << max << endl;
    }
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值