C Governing sand
题意:给你N种树,第一列是高度,第二列是砍伐一颗的代价,第三列为多少颗。需要让最高的树的个数是所有树个数的一半多,问达到这样的最小的代价为多少。
闲话:比赛最后12分钟才想到一个合理的优化,赛后才A出来,也是很难受了。
题解:暴力+贪心枚举。
A:大致思路:无论在什么情况下,那颗树的高度都是N颗树的高度中的一颗,那么遍历整个N,假定tree[i]的高度为目标树的高度,然后砍掉比这颗树高的所有树(这里用前缀和来维护),接着去砍掉前面的树来符合题目要求(在这里找到的时候就去贪心找代价最小的树,然后一直砍到符合数目)。
B:在砍前面的树的时候,用一个长为200的cost2来维护。树的高度从最小的那颗开始一直到最大的那棵树。每经过一棵树的高度的时候,把那棵树的数目加到对应砍伐代价的cost2[cost]中,然后后面的树,要砍伐的前面的树的个数都从这个数组中选取。整个时间复杂度为O(200N)。
C:本题还要去注意一下离散化的树的高度,因为可能有好几种树高度一样,但砍伐代价和个数不同的情况。
代码:
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int mx = 1e5 + 7;
typedef long long ll;
ll n;
ll sump[mx];
ll sumc[mx];
struct node {
ll h, c, p,id;
}tree[mx], ctree[mx];
struct node2 {
ll c, id, p, h;
}cost[mx];
bool cmp(node a, node b) {
return a.h < b.h;
}
bool cmp2(node2 a, node2 b) {
return a.c < b.c;
}
node tran[mx];
ll SUM(ll c[207]) {
ll s = 0;
for (int i = 1; i <= 207; i++)
s = s+c[i]*i;
return s;
}
ll mainwork(ll len) {
ll min = 1e18;
ll cost2[300] = { 0 };
for (int i = 1; i <= len; i++) {
ll re = tree[i].p * 2 - 1;
ll needc = sump[len] - re;
ll pay = 0;
needc -= (sump[len] - sump[i]);
if (needc <= 0)
;
else {
for (int j = 1; j <= 207; j++)
{
if (cost2[j] > 0) {
if (needc >= cost2[j]) {
needc -= cost2[j];
pay += j * cost2[j];
}
else {
pay += j * needc;
needc = 0;
}
}
}
}
int f = 0;
for (int j = 0; j <= n; j++) {
if (tree[i].h == ctree[i + j].h) {
cost2[ctree[i + j].c] += ctree[i + j].p, f=1;
}
else if (f)
break;
}
pay += (sumc[n] - SUM(cost2));
if (pay <= 0)
min = pay;
else if (min > pay)
min = pay;
}
return min;
}
ll qc(ll n) {
ll len = 1;
ctree[1] = tran[1] = tree[1];
for (int i = 2; i <= n; i++) {
ctree[i] = tree[i];
if (tree[i].h == tree[i - 1].h) {
tree[i].p = tree[i].p + tree[i-1].p;
tran[len] = tree[i];
}
else {
len++;
tran[len] = tree[i];
}
}
for (int i = 1; i <= len; i++) {
tree[i] = tran[i];
}
return len;
}
int main() {
while (scanf("%lld", &n) != EOF) {
for (int i = 1; i <= n; i++)
{
ll a, b, c;
scanf("%lld%lld%lld", &a, &b, &c);
tree[i].h = a, tree[i].c = b, tree[i].p = c,tree[i].id = i;
cost[i].c = b, cost[i].id = i, cost[i].p = c, cost[i].h = a;
}
sort(cost + 1, cost + 1 + n, cmp2);
sort(tree + 1, tree + 1 + n, cmp);
ll len =qc(n); //去重 离散化
sumc[0] = sump[0] = 0;
for (int i = 1; i <= n; i++) {
sumc[i] = sumc[i - 1] + ctree[i].c*ctree[i].p;
}
for (int i = 1; i <= len; i++) {
sump[i] = sump[i - 1] + tree[i].p;
}
ll min = mainwork(len);
printf("%lld\n", min);
}
return 0;
}