2151: 种树
Time Limit: 10 Sec Memory Limit: 259 MB
Submit: 711 Solved: 396
Description
A城市有一个巨大的圆形广场,为了绿化环境和净化空气,市政府决定沿圆形广场外圈种一圈树。园林部门得到指令后,初步规划出n个种树的位置,顺时针编号1到n。并且每个位置都有一个美观度Ai,如果在这里种树就可以得到这Ai的美观度。但由于A城市土壤肥力欠佳,两棵树决不能种在相邻的位置(i号位置和i+1号位置叫相邻位置。值得注意的是1号和n号也算相邻位置!)。最终市政府给园林部门提供了m棵树苗并要求全部种上,请你帮忙设计种树方案使得美观度总和最大。如果无法将m棵树苗全部种上,给出无解信息。
输入的第一行包含两个正整数n、m。第二行n个整数Ai。
输出一个整数,表示最佳植树方案可以得到的美观度。如果无解输出“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
一个很神的贪心……
首先,如果没有位置的限制,就可以按照美观度从大到小贪心了……
但是这里有位置的限制……
例如: a1, a2, a3
a1 < a2, a3 < a2, a1 + a3 > a2
如果按照之前的贪心,一定是选a2,那样a1, a3就不能选了。可是如果选a1, a2比选a3更优呢!!!
正解呢……是要用到链表,来存储previous和next,每次取走一个数,再在原位置插入W[previous] +W[next] - W[now],同时在链表中删去previous和next。若再次取到这个数字就表明取走previous和next,不取now。
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
const int SZ = 200010;
struct TREE
{
int pos, w;
};
set<TREE> Q;
set<TREE>::iterator it;
bool vis[SZ];
int pre[SZ], nxt[SZ], w[SZ], n, m;
bool operator < (const TREE &a, const TREE &b)
{
return a.w == b.w ? a.pos > b.pos : a.w > b.w;
}
int read()
{
int num = 0, f = 1; char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -1; c = getchar();}
while('0' <= c && c <= '9'){num = num * 10 + (c - '0'); c = getchar();}
return num * f;
}
void erase(int pos)
{
if(!pos) return ;
it = Q.find((TREE){pos, w[pos]});
if(it != Q.end()) Q.erase(it);
}
int get_ans()
{
int ans = 0;
for(int i = 1; i <= m; i++)
{
TREE now = *Q.begin();
Q.erase(Q.begin());
ans += now.w;
erase(pre[now.pos]); erase(nxt[now.pos]);
w[now.pos] = w[pre[now.pos]] + w[nxt[now.pos]] - w[now.pos];
pre[now.pos] = pre[pre[now.pos]]; nxt[now.pos] = nxt[nxt[now.pos]];
nxt[pre[now.pos]] = pre[nxt[now.pos]] = now.pos;
Q.insert((TREE){now.pos, w[now.pos]});
}
return ans;
}
int main()
{
n = read(), m = read();
for(int i = 1; i <= n; i++)
{
w[i] = read();
pre[i] = i - 1, nxt[i] = i + 1;
Q.insert((TREE){i, w[i]});
}
pre[1] = n, nxt[n] = 1;
if(2 * m > n) puts("Error!");
else printf("%d", get_ans());
return 0;
}