题目描述
就so.in/.out
【背景描述】
一排 N 个数, 第 i 个数是 Ai , 你要找出 K 个不相邻的数, 使得他们的和最大。
请求出这个最大和。
【输入格式】
第一行两个整数 N 和 K。
接下来一行 N 个整数, 第 i 个整数表示 Ai 。
【输出格式】
一行一个整数表示最大和, 请注意答案可能会超过 int 范围
【样例输入】
3 2
4 5 3
【样例输出】
7
【数据范围】
对于 20% 的数据, N, K ≤ 20 。
对于 40% 的数据, N, K ≤ 1000 。
对于 60% 的数据, N, K ≤ 10000 。
对于 100% 的数据, N, K ≤ 100000 , 1 ≤ Ai ≤ 1000000000。
贪心,用一个堆来维护最大权值,之后每次从堆里取出堆顶元素,将它和相邻的两个元素合并并修改权值,这可以用链表来实现。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<set>
#define mem(a,b) memset(a,b,sizeof(a))
#define maxn 100005
using namespace std;
typedef long long ll;
inline int read()
{ char c=getchar();int x=0,y=1;
while(c<'0'||c>'9'){if(c=='-') y=-1;c=getchar();}
while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*y;
}
struct node
{ int id;ll w;
friend bool operator <(const node& a,const node& b){ return a.w==b.w?a.id<b.id:a.w>b.w;}
};
set<node>q;
int n,K,pre[maxn],nex[maxn];
ll A[maxn],ans;
void solve()
{ while(K--)
{ node tmp=*q.begin();q.erase((node){tmp.id,tmp.w});
ans+=A[tmp.id];
A[tmp.id]=A[pre[tmp.id]]+A[nex[tmp.id]]-A[tmp.id];
q.erase((node){pre[tmp.id],A[pre[tmp.id]]});
q.erase((node){nex[tmp.id],A[nex[tmp.id]]});
q.insert((node){tmp.id,A[tmp.id]});
if(pre[pre[tmp.id]]) nex[pre[pre[tmp.id]]]=tmp.id;
if(nex[nex[tmp.id]]) pre[nex[nex[tmp.id]]]=tmp.id;
pre[tmp.id]=pre[pre[tmp.id]];
nex[tmp.id]=nex[nex[tmp.id]];
}
}
int main()
{ //freopen("so13.in","r",stdin);
//freopen("so.out","w",stdout);
n=read();K=read();
A[0]=-1e16;
for(int i=1;i<=n;i++)
A[i]=read(),pre[i]=i-1,nex[i]=i+1,q.insert((node){i,A[i]});
nex[n]=0;
solve();
printf("%lld",ans);
return 0;
}