2151: 种树
Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 1510 Solved: 830
[Submit][Status][Discuss]
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
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
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
HINT
Source
试题分析
对于没有限制相邻两点没有种树时,就是一个普通贪心,取最大m个即可。但是现在有限制条件,所以对于贪心我们又是不会取到最优的情况,所以这又有一个新操作姿势--可撤销贪心。就像对于网络流建反边一样,给程序一个反悔机会,对于挑选现在最大的,设当前前驱为pre,后继为nex,当前位置为x,删除pre与nex,加入val[pre]+val[nex]-val[x],证明略。然后用链表维护即可。
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<queue> using namespace std; inline int read(){ int f=1,ans=0;char c=getchar(); while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();} while(c>='0'&&c<='9'){ans=ans*10+c-'0';c=getchar();} return f*ans; } priority_queue<pair<int,int> >que; const int N=200001; int mark[N],pre[N],m,nex[N],n,a[N]; void del(int x){ mark[x]=1; int l=pre[x],r=nex[x]; pre[x]=0,nex[x]=0; pre[r]=l,nex[l]=r; } int ans=0; int get(){ while(mark[que.top().second]) que.pop(); int u=que.top().second;que.pop(); int val=a[u]; a[u]=a[pre[u]]+a[nex[u]]-a[u]; del(pre[u]),del(nex[u]); que.push(make_pair(a[u],u)); return val; } int main(){ n=read(),m=read(); if(m*2>n){printf("Error!");return 0;} for(int i=1;i<=n;i++) a[i]=read(); for(int i=1;i<=n;i++) pre[i]=i-1,nex[i]=i+1; pre[1]=n,nex[n]=1; for(int i=1;i<=n;i++) que.push(make_pair(a[i],i)); for(int i=1;i<=m;i++) ans+=get(); printf("%d\n",ans); }