Problem Description
HDU’s n 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 n classrooms.
The total cost consists of two parts. Building a candy shop at classroom i would have some cost ci. For every classroom P without any candy shop, then the distance between P and the rightmost classroom with a candy shop on P’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.
Input
The input contains several test cases, no more than 10 test cases.
In each test case, the first line contains an integer n(1≤n≤3000), denoting the number of the classrooms.
In the following n lines, each line contains two integers xi,ci(−109≤xi,ci≤109), denoting the coordinate of the i-th classroom and the cost of building a candy shop in it.
There are no two classrooms having same coordinate.
Output
For 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 1
Sample Output
5
11
题意:给你n个教学楼的位置和建商店的花费,如果一个教学楼没有商店,则需要到左面有商店的楼,花费为距离差。问最小花费使得所有楼都可以买到东西。
题解:首先最左面的楼是必须要建商店的。考虑dp,dp[i][j]表示在第i栋楼是否建商店的最小花费(0不建,1建)。
j==1: 则 dp[i][1]=min(dp[i-1][1],dp[i-1][0])+建商店花费;
j==0:则我们找到左面建商店的楼j,dp[i][0]=dp[j][1]+(j+1至i楼到j栋的花费)。注意位置不是按升序给的,要排个序。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<map>
#define NI freopen("in.txt","r",stdin);
#define NO freopen("out.txt","w",stdout);
using namespace std;
typedef long long int ll;
typedef pair<int,int>pa;
const int N=2e5+10;
const int MOD=1e9+7;
const ll INF=1e18;
int read()
{
int x=0;
char ch = getchar();
while('0'>ch||ch>'9')ch=getchar();
while('0'<=ch&&ch<='9')
{
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return x;
}
/************************************************************/
struct node
{
ll id,c;
bool operator <(const node &t)const{
return id<t.id;
}
}a[N];
int t,n;
ll dp[N][2];
int main()
{
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
scanf("%lld%lld",&a[i].id,&a[i].c);
sort(a+1,a+1+n);
dp[1][1]=a[1].c;
dp[1][0]=INF;
for(int i=2;i<=n;i++)
{
dp[i][1]=min(dp[i-1][1],dp[i-1][0])+a[i].c;
dp[i][0]=INF;
ll res=0;
for(int j=i-1;j>=1;j--)
{
res+=(i-j)*(a[j+1].id-a[j].id);
dp[i][0]=min(dp[i][0],dp[j][1]+res);
}
}
printf("%lld\n",min(dp[n][0],dp[n][1]));
}
}