题目链接点击打开链接
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
- the sum of the costs of stuck pins;
- the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output the single number — the least fine you will have to pay.
3 2 3 3 4 1 2
5
4 1 7 3 1 5 10 6 1
11
我们先将每个点按照坐标升序排序
dp[i][j]中一维表示进行到第几个点,二维表示最后一个被固定的点
则递推到i点时分两种情况:
1: i点固定(加上需要固定的费用,i点后的小球不会往前滚),那么有dp[i][i]=min(dp[i][i],dp[i-1][j]+p[i].c);
2: i点不固定(则需要加上从j点向前滚到i点的费用),那么有dp[i][j]=min(dp[i][j],dp[i-1][j]+p[i].x-p[j].x);
#include<bits/stdc++.h>
#define LL long long
#define inf 0x3f3f3f3f
using namespace std;
struct node
{
int x;
int c;
}p[3005];
LL dp[3005][3005];
bool cmp(node one,node two)
{
return one.x<two.x;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&p[i].x,&p[i].c);
}
sort(p+1,p+1+n,cmp);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
dp[i][j]=1e18;
}
dp[1][1]=p[1].c;
for(int i=2;i<=n;i++)
{
for(int j=1;j<i;j++)
{
dp[i][j]=min(dp[i][j],dp[i-1][j]+p[i].x-p[j].x);
dp[i][i]=min(dp[i][i],dp[i-1][j]+p[i].c);
}
}
LL ans=1e18;
for(int i=1;i<=n;i++)
ans=min(ans,dp[n][i]);
printf("%ld\n",ans);
}