20160802 推销员 贪心 堆

这里写图片描述

这题最重要的结论就是X=i时的选择必定包含X=i-1时的所有点。。。这样我们记录当前选择的最远距离,在其左右分别维护一个堆,左边的不算距离,右边的算距离(要减去当前最远距离),每次从两堆顶中选择最优解,如果更新了最远距离,就要将右边堆中这个距离左边的点都拿出来减去距离扔到左堆里。重复N次即可。
这个时候再次体现了万恶的STL数据封装有多坑,要想直接将某一编号的节点从堆中删除,只能使用带有pos的手写堆。

自己的代码:

#include<cstdio>
#define gm 100001
using namespace std;
typedef unsigned long long ull;
int n;
int s[gm],a[gm];
ull ans[gm]={};
int lst=0;
struct zh
{
    int no;
    int val;
    bool operator <(const zh &b) const
    {return val<b.val;}
}hp[2][gm];
int pos[2][gm];
int figr[2]={};
void add(int k,const zh &v)
{
    zh* h=hp[k];
    int* p=pos[k];
    int x=++figr[k];
    while(x>1)
    {
        if(h[x>>1]<v)
        {
            h[x]=h[x>>1];
            p[h[x].no]=x;
            x>>=1;
        }
        else break;
    }
    h[x]=v;
    p[v.no]=x;
}
void del(int k,int popoqqq)
{
    zh* h=hp[k];
    int* p=pos[k];
    zh v=h[figr[k]--];
    int x=p[popoqqq],j;
    while((x<<1)<=figr[k])
    {
        j=x<<1;
        if(j+1<=figr[k]&&h[j]<h[j+1]) j++;
        if(v<h[j])
        {
            h[x]=h[j];
            p[h[x].no]=x;
            x=j;
        }
        else break;
    }
    h[x]=v;
    p[v.no]=x;
}
#define top(k) figr[k]?hp[k][1]:(zh){0,0}
int main()
{
    freopen("salesman.in","r",stdin);
    freopen("salesman.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++) {scanf("%d",&s[i]);s[i]*=2;}
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=n;i++) add(1,(zh){i,s[i]+a[i]});
    for(int i=1;i<=n;i++)
    {
        zh s1=top(0),s2=top(1),s3;
        ans[i]=ans[i-1];
        if(s1.val<s2.val-s[lst])
        {
            for(int j=lst+1;j<s2.no;j++)
            {
                s3=hp[1][pos[1][j]];
                del(1,j);
                s3.val-=s[j];
                add(0,s3);
            }
            ans[i]+=s2.val-s[lst];
            lst=s2.no;
            del(1,s2.no);
        }
        else
        {
            ans[i]+=s1.val;
            del(0,s1.no);
        }
    }
    for(int i=1;i<=n;i++)
    printf("%llu\n",ans[i]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值