2106: 种树
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 86 Solved: 25
[ Submit][ Status][ Web Board]
Description
A城市有一个巨大的圆形广场,为了绿化环境和净化空气,市政府决定沿圆形广场外圈种一圈树。园林部门 得到指令后,初步规划出n个种树的位置,顺时针编号1到n。并且每个位置都有一个美观度Ai,如果在这里种树就可以得到这Ai的美观度。但由于A城市土壤 肥力欠佳,两棵树决不能种在相邻的位置(i号位置和i+1号位置叫相邻位置。值得注意的是1号和n号也算相邻位置!)。
最终市政府给园林部门提供了m棵树苗并要求全部种上,请你帮忙设计种树方案使得美观度总和最大。如果无法将m棵树苗全部种上,给出无解信息。
Input
输入的第一行包含两个正整数n、m。
第二行n个整数Ai。
Output
输出一个整数,表示最佳植树方案可以得到的美观度。如果无解输出“Error!”,不包含引号。
Sample Input
7
3
1
2 3 4 5 6 7
Sample Output
15
HINT
对于全部数据,满足1<=m<=n<=30;
其中90%的数据满足m<=n<=20
-1000<=Ai<=1000
Source
//贪心,刚开始时一直错,自己修改的是x[i]的pre和next,并未修改队列中的x[i]的pre和next。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
struct node
{
int ai;
int index;
friend bool operator < (const node &A,const node &B)
{
return A.ai<B.ai;
}
};
int pre[40],next[40],v[40];
priority_queue<node>q;
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m))
{
node x[40];
int i,j,sum=0;
while(!q.empty())
q.pop();
memset(v,0,sizeof(v));
for(i=1;i<=n;i++)
{
scanf("%d",&x[i].ai);
x[i].index=i;
q.push(x[i]);
if(i==1)pre[i]=n;
else pre[i]=i-1;
if(i==n)next[i]=1;
else next[i]=i+1;
}
if(m>n/2)
{
printf("Error!\n");
continue;
}
while(m)
{
node temp=q.top();
if(v[temp.index]==1)
{
q.pop();
continue;
}else
{
q.pop();
sum+=temp.ai;
//cout<<temp.ai<<endl;
int tempNext=next[temp.index];
int tempPre=pre[temp.index];
v[tempNext]=v[tempPre]=1;
x[temp.index].ai=temp.ai=x[tempNext].ai+x[tempPre].ai-temp.ai;
pre[temp.index]=pre[tempPre];
next[temp.index]=next[tempNext];
int tempNnext=next[tempNext];
int tempPpre=pre[tempPre];
pre[tempNnext]=temp.index;
next[tempPpre]=temp.index;
q.push(temp);
/*int k=0;
node xx[40];
while(!q.empty())
{
node now=q.top();
if(v[now.index]==0)
{
cout<<now.ai<<"-"<<now.index<<" "<<pre[now.index]<<" "<<next[now.index]<<endl;
}
xx[k++]=now;
q.pop();
}
cout<<endl;
for(i=0;i<k;i++)
q.push(xx[i]);*/
m--;
}
}
printf("%d\n",sum);
}
return 0;
}
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int main()
{
queue<int>q;
int a=3;
q.push(a);
a=4;
printf("a的地址:%p\n",&a);
while(!q.empty())
{
printf("q.front()的地址:%p\n",&q.front());
printf("a=%d\n",a);
printf("q.front()=%d\n",q.front());
q.pop();
}
return 0;
}
说明a进入队列后,开辟了一个新的空间;