AC日记——Mice and Holes codeforces 797f

797F - Mice and Holes

 

思路:

  XXYXX

 

代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

#define maxn 5005
#define ll long long

struct HoleType {
    ll x,c;
};
struct HoleType hole[maxn];

ll n,m,mice[maxn],s[maxn],sum,dp[maxn][maxn],que[maxn];

inline void in(ll &now)
{
    ll if_z=1;now=0;
    char Cget=getchar();
    while(Cget>'9'||Cget<'0')
    {
        if(Cget=='-') if_z=-1;
        Cget=getchar();
    }
    while(Cget>='0'&&Cget<='9')
    {
        now=now*10+Cget-'0';
        Cget=getchar();
    }
    now*=if_z;
}

bool cmp(HoleType aa,HoleType bb)
{
    return aa.x<bb.x;
}

int main()
{
    in(n),in(m);
    for(ll i=1;i<=n;i++) in(mice[i]);
    for(ll i=1;i<=m;i++) in(hole[i].x),in(hole[i].c),sum+=hole[i].c;
    if(sum<n)
    {
        printf("-1\n");
        return 0;
    }
    sort(mice+1,mice+n+1),sort(hole+1,hole+m+1,cmp);
    memset(dp,0x7f,sizeof(dp)),dp[0][0]=0;
    for(ll i=1;i<=m;i++)
    {
        ll head=0,tail=-1;
        for(ll j=1;j<=n;j++) s[j]=s[j-1]+abs(hole[i].x-mice[j]);
        for(ll j=0;j<=n;j++)
        {
            while(head<=tail&&que[head]<j-hole[i].c) head++;
            while(tail>=head&&dp[i-1][j]-s[j]<=dp[i][que[tail]]-s[que[tail]]) tail--;
            que[++tail]=j,dp[i][j]=dp[i-1][que[head]]-s[que[head]]+s[j];
        }
    }
    cout<<dp[m][n];
    return 0;
}

 

posted @ 2017-05-10 17:41  IIIIIIIIIU  阅读(188)  评论(0编辑  收藏  举报