HDU’s
nn classrooms are on a line ,which can be considered as a number line. Each classroom has a coordinate. Now Little Q wants to build several candy shops in these
nn classrooms.
The total cost consists of two parts. Building a candy shop at classroom ii would have some cost cici. For every classroom PP without any candy shop, then the distance between PP and the rightmost classroom with a candy shop on PP's left side would be included in the cost too. Obviously, if there is a classroom without any candy shop, there must be a candy shop on its left side.
Now Little Q wants to know how to build the candy shops with the minimal cost. Please write a program to help him.
InputThe input contains several test cases, no more than 10 test cases.
The total cost consists of two parts. Building a candy shop at classroom ii would have some cost cici. For every classroom PP without any candy shop, then the distance between PP and the rightmost classroom with a candy shop on PP's left side would be included in the cost too. Obviously, if there is a classroom without any candy shop, there must be a candy shop on its left side.
Now Little Q wants to know how to build the candy shops with the minimal cost. Please write a program to help him.
In each test case, the first line contains an integer n(1≤n≤3000)n(1≤n≤3000), denoting the number of the classrooms.
In the following nn lines, each line contains two integers xi,ci(−109≤xi,ci≤109)xi,ci(−109≤xi,ci≤109), denoting the coordinate of the ii-th classroom and the cost of building a candy shop in it.
There are no two classrooms having same coordinate.OutputFor each test case, print a single line containing an integer, denoting the minimal cost.Sample Input
3 1 2 2 3 3 4 4 1 7 3 1 5 10 6 1Sample Output
5 11
题目大概:
在一条线上有很多教室,可以在教室建立糖果店,每个教室都有坐标和建立糖果店的费用。如果该教室没有建立糖果店,那么在这个教室左边的糖果店到此教室的距离为此教室的费用,问最小的修建糖果店的费用是多少。
思路:
dp【i】【j】为到第i个教室,前一个糖果店的位置是j,的最小费用是多少。
分两种,一是在这里修建糖果店。dp【i】【i】=min(dp【i】【i】,dp【i-1】【j】+v【i】)(1<=j<i)。
二是不修建糖果店。dp【i】【j】=min(dp【i】【j】,dp【i-1】【j】+d【i】-d【j】)(1<=j<i)。
当然,第一个教室必须修建糖果店。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=3300;
long long dp[maxn][maxn];
struct poin
{
int x,v;
}a[maxn];
int cmp(poin q,poin w)
{
return q.x<w.x;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x,&a[i].v);
}
sort(a+1,a+1+n,cmp);
memset(dp,0x3f3f3f3f,sizeof(dp));
dp[1][1]=a[1].v;
for(int i=2;i<=n;i++)
{
dp[i][i]=dp[i][i-1]+a[i].v;
for(int j=1;j<i;j++)
{
dp[i][j]=min(dp[i][j],dp[i-1][j]+a[i].x-a[j].x);
dp[i][i]=min(dp[i][i],dp[i-1][j]+a[i].v);
}
}
long long sum=0x3f3f3f3f;
for(int i=1;i<=n;i++)
{
sum=min(sum,dp[n][i]);
}
printf("%lld\n",sum);
}
return 0;
}