HDU 6024 Building Shops[dp]

题意:给定n个点(n<=3000),每个点有个wi,对于每个点,选择的代价为wi,不选择的代价为跟他距离最近的左边的点的距离。问最小代价为多少。


分析:dp[i]表示最后取的点为 i 时的最小代价,那么转移的话就是dp[i] = min(dp[i],dp[j]+sum[i - 1] - sum[j] - x[j]*(i-j-1) + w[i]);

其中,sum[i]为1-i的所有点的坐标之和,复杂度为O(n^2),好像能通过斜率优化到O(n),目前不会,,回头再补。


以下是代码。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
//#include
#include
#include
#include
using namespace std;
#define _____ ios::sync_with_stdio(false); cin.tie(0);
#define ull unsigned long long
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pairpii;
typedef pairpll;
typedef pairpdd;
const double eps = 1e-6;
const int MAXN = 300005;
const int MAXM = 5005;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
const ll MOD = 1000000007;
struct lx {
    ll xi, ci;
    friend bool operator<(const lx a, const lx b) {
        return a.xi < b.xi;
    }
}tmp[3005];
ll dp[3005];
ll sum[3005];
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        memset(dp, LINF, sizeof(dp));
        for (int i = 1; i <= n; ++i)scanf("%I64d%I64d", &tmp[i].xi, &tmp[i].ci);
        sort(tmp + 1, tmp + n + 1); sum[1] = tmp[1].xi;
        for (int i = 2; i <= n; ++i)sum[i] = sum[i - 1] + tmp[i].xi;
        dp[1] = tmp[1].ci;
        for (int i = 2; i <= n; ++i)
        {
            for (int j = 1; j < i; ++j)
            {
                dp[i] = min(dp[i], dp[j] + sum[i - 1] - sum[j] - (i - j - 1)*tmp[j].xi + tmp[i].ci);
            }
        }
        ll ans = LINF;
        //for (int i = 1; i <= n; i++)printf("%I64d\n", dp[i]);
        for (int i = 1; i <= n; ++i)ans = min(ans, dp[i] + sum[n] - sum[i] - (n - i)*tmp[i].xi);
        printf("%I64d\n", ans);
    }
}


你可能感兴趣的:(HDU)