Repairman - HDU 3024 dp

来源:互联网 发布:jquery 数组遍历 编辑:程序博客网 时间:2024/06/15 20:40

Repairman

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 128    Accepted Submission(s): 38


Problem Description
The traveling repairman problem (TRP) is classical NP-Hard problem, which is also known as minimum latency problem (MLP) and delivery man problem. Suppose that we have a graph with n nodes, in each one there is a machine that has to be repaired, and there is only one repairman. We are given the time required by the repairman to travel among nodes. The objective is to find a tour that minimizes the total waiting time of all the machines. (ignore time of repairing)

Now for simplicity, we place all nodes on a straight line. Your task is to find out smallest sum of waiting time of all the machines.
 

Input
The first line of input contains a single integer T, which is the number of test case. Each case starts with a line containing a single integer N (1 ≤ N ≤ 400), the number of nodes. The next line gives a list of N corrdinate of nodes. Each corrdinate is a integer in the range [-1000, 1000]. Consecutive integers are separated by a single space charcter. The repairman will depart from origin. Suppose he travels at unit speed.
 

Output
For each case, output one line with the smallest sum of waiting time.
 

Sample Input
22-1 23-1 1 2
 

Sample Output
58


题意:在一个一维的数轴上有N个点,每个点上有一个需要修的机器,一个人最开始在0位置,单位时间移动一个单位的距离,问所有机器未修理的时间和最少是多少。

思路:首先让dp[i][j][0 | 1]表示修理i到j个机器时所有机器未修理时间的最小值。初始化的时候让dp[i][i][0]=dp[i][i][1]=abs(num[i])*n; 因为一开始你到i点事时间就是距离,然后因为这段时间所有的机器都未修理,所以时间是距离*n。剩下的转移方程就看代码吧,很容易理解的。

AC代码如下:

#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<iostream>using namespace std;int dp[410][410][2],num[410];int main(){ int t,n,i,j,k;  scanf("%d",&t);  while(t--)  { scanf("%d",&n);    for(i=1;i<=n;i++)     scanf("%d",&num[i]);    sort(num+1,num+1+n);    for(i=1;i<=n;i++)     dp[i][i][0]=dp[i][i][1]=abs(num[i])*n;    for(i=n;i>=1;i--)     for(j=i+1;j<=n;j++)     { dp[i][j][0]=min(dp[i+1][j][0]+(num[i+1]-num[i])*(n-j+i),dp[i+1][j][1]+(num[j]-num[i])*(n-j+i));       dp[i][j][1]=min(dp[i][j-1][1]+(num[j]-num[j-1])*(n-j+i),dp[i][j-1][0]+(num[j]-num[i])*(n-j+i));     }    printf("%d\n",min(dp[1][n][0],dp[1][n][1]));  }}



0 0