HDU 6024 Building Shops(DP)

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]));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章