贪心+priority_queue。
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #define maxn 200050 using namespace std; long long n,val[maxn],ans=0,m; bool vis[maxn]; struct node { long long w,pos; friend bool operator < (node x,node y) { return x.w<y.w; } }; priority_queue <node> q; int main() { memset(vis,true,sizeof(vis)); scanf("%lld%lld",&n,&m); for (long long i=0;i<n;i++) { scanf("%lld",&val[i]); node now; now.w=val[i];now.pos=i; q.push(now); } if (m>=(n/2)+1) {printf("Error!\n");return 0;} long long cnt=0; do { node now=q.top(); q.pop(); if (vis[now.pos]==true) { cnt++; long long left=(now.pos-1+n)%n,right=(now.pos+1+n)%n; while (vis[left]==false) left=(left-1+n)%n; while (vis[right]==false) right=(right+1+n)%n; vis[left]=false;vis[right]=false; node then; then.w=val[left]+val[right]-val[now.pos]; then.pos=now.pos; q.push(then); ans=ans+val[now.pos]; val[now.pos]=val[left]+val[right]-val[now.pos]; } }while (cnt!=m); printf("%lld\n",ans); return 0; }