Codeforces 854C Planning(贪心+堆)

  贪心:让代价大的尽量移到靠前的位置。

  做法:先让前k个数加进堆里,枚举k+1~n+k,每次把新元素加进堆后找到最大代价放在当前位置即可。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=500010;
struct poi{int c,pos;};
priority_queue<poi>q;
bool operator<(poi a,poi b){return a.c<b.c;}
int n,k;
int a[maxn],ansi[maxn];
ll ans;
void read(int &k)
{
    int f=1;k=0;char c=getchar();
    while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    while(c<='9'&&c>='0')k=k*10+c-'0',c=getchar();
    k*=f;
}
int main()
{
    read(n);read(k);
    for(int i=1;i<=n;i++)read(a[i]);
    for(int i=1;i<=k;i++)q.push((poi){a[i],i});
    for(int i=k+1;i<=n+k;i++)
    {
        if(i<=n)q.push((poi){a[i],i});
        poi t=q.top();q.pop();
        ans+=1ll*t.c*(i-t.pos);
        ansi[t.pos]=i;
    }
    printf("%I64d
",ans);
    for(int i=1;i<=n;i++)printf("%d ",ansi[i]);
}
View Code
原文地址:https://www.cnblogs.com/Sakits/p/7489309.html