Description
A城市有一个巨大的圆形广场,为了绿化环境和净化空气,市政府决定沿圆形广场外圈种一圈树。园林部门得到指令后,初步规划出n个种树的位置,顺时针编号1到n。并且每个位置都有一个美观度Ai,如果在这里种树就可以得到这Ai的美观度。但由于A城市土壤肥力欠佳,两棵树决不能种在相邻的位置(i号位置和i+1号位置叫相邻位置。值得注意的是1号和n号也算相邻位置!)。最终市政府给园林部门提供了m棵树苗并要求全部种上,请你帮忙设计种树方案使得美观度总和最大。如果无法将m棵树苗全部种上,给出无解信息。
Input
输入的第一行包含两个正整数n、m。第二行n个整数Ai。
Output
输出一个整数,表示最佳植树方案可以得到的美观度。如果无解输出“Error!”,不包含引号。
Sample Input
【样例输入1】
7 3
1 2 3 4 5 6 7
【样例输入2】
7 4
1 2 3 4 5 6 7
Sample Output
【样例输出1】
15
【样例输出2】
Error!
【数据规模】
对于全部数据:m<=n;
-1000<=Ai<=1000
N的大小对于不同数据有所不同:
数据编号 N的大小 数据编号 N的大小
1 30 11 200
2 35 12 2007
3 40 13 2008
4 45 14 2009
5 50 15 2010
6 55 16 2011
7 60 17 2012
8 65 18 199999
9 200 19 199999
10 200 20 200000
题解
利用双向链表,每次贪心取出最大的,然后用a[nxt[x]]+a[pre[x]]-a[x]代替它
代码
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int ans;
int n,m;
int a[200005],pre[200005],nxt[200005];
bool mark[200005];
priority_queue<pa,vector<pa> >q;
inline void del(int x)
{
mark[x]=1;
pre[nxt[x]]=pre[x];
nxt[pre[x]]=nxt[x];
}
int main()
{
n=read();m=read();
if (m>n/2) return puts("Error!"),0;
for (int i=1;i<=n;i++)
{
a[i]=read();
nxt[i]=i+1>n?1:i+1;
pre[i]=i-1<1?n:i-1;
q.push(make_pair(a[i],i));
}
for (int i=1;i<=m;i++)
{
while (mark[q.top().second]) q.pop();
int x=q.top().second;ans+=a[x];
q.pop();
a[x]=a[pre[x]]+a[nxt[x]]-a[x];
q.push(make_pair(a[x],x));
del(pre[x]);del(nxt[x]);
}
printf("%d",ans);
return 0;
}