算法提高 种树
最终市政府给园林部门提供了m棵树苗并要求全部种上,请你帮忙设计种树方案使得美观度总和最大。如果无法将m棵树苗全部种上,给出无解信息。
第二行n个整数Ai。
1 2 3 4 5 6 7
1 2 3 4 5 6 7
其中90%的数据满足m<=n<=20
-1000<=Ai<=1000
#include <iostream>
#include <stdio.h>
#include<vector>
#include<queue>
#include<algorithm>
#define N 200010
using namespace std;
struct Data
{
int i, ai;
};
struct cmp
{
bool operator()(Data &t1, Data &t2)
{
return t1.ai < t2.ai;
}
};
priority_queue<Data,vector<Data>, cmp> q;
int n, m;
int a[N];
int pre[N], next[N];
bool visit[N];
void del(int k)
{
visit[k] = true;
int temp1 = pre[k], temp2 = next[k];
pre[k] = next[k] = -1;
next[temp1] = temp2;
pre[temp2] = temp1;
}
void chuli(Data k)
{
Data data;
data.ai = a[pre[k.i]] + a[next[k.i]] - k.ai;
a[k.i] = data.ai;
data.i = k.i;
q.push(data);
del(pre[k.i]);
del(next[k.i]);
}
int main()
{
scanf("%d%d", &n, &m);
int i;
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
if (m > n / 2)
{
printf("Error!\n");
return 0;
}
for (i = 0; i < n - 1; i++)
next[i] = i + 1;
next[n - 1] = 0;
for (i = 1; i < n; i++)
pre[i] = i - 1;
pre[0] = n - 1;
for (i = 0; i < n; i++)
{
Data data;
data.i = i;
data.ai = a[i];
q.push(data);
}
int res = 0;
while (m--)
{
while (!q.empty() && visit[q.top().i])
q.pop();
Data data = q.top();
q.pop();
res += data.ai;
//printf("%d\n", res);
//getchar();
chuli(data);
}
printf("%d\n", res);
return 0;
}
2220




被折叠的 条评论
为什么被折叠?



