题目地址:登录—专业IT笔试面试备考平台_牛客网
题目大致意思:
解法:肯定是先按照高度排个序,然后每次依次删除这个高度,而且在每一次遍历的时候看下这个高度的数量有多少,记为now_num,然后和前面比它矮的树的数量记为pre_num,比较大小,因为题目要求pre_num<now_num,那么就需要在前面删除pre_num-now_num+1棵树,并且要求这个删除的值最少,那么可以用权值线段树,当然也可以暴力,因为C的最大值也就200,但是这里为了练习权值线段树,所以用权值线段树来做。维护一个cnt数组表示子树个数,sum数组表示子树的权值。然后就是正常的线段树操作了。
#include<bits/stdc++.h>
#define FRD freopen("in.txt", "r", stdin)
#define __ctz(x) __builtin_ctz(x) //返回二进制下末尾有几个零
#define __ffs(x) __builtin_ffs(x) //返回二进制下最后一个1的位置,从1开始
#define ms(x) memset(x,0,sizeof(x))
#define pb(x) push_back(x)
#define lson (id<<1)
#define rson (id<<1|1)
#define mid ((l+r)>>1)
using namespace std;
typedef long long int LL;
const int N = 1e5+7;
int n;
LL cnt[N], sum[N];
struct Node{
LL h, c, p;
bool operator < (const Node &A) const{
return h < A.h;
}
} A[N];
void my_min(LL &A, const LL &B) {
if (A > B) A = B;
}
void push_up(int id){
cnt[id] = cnt[lson]+cnt[rson];
sum[id] = sum[lson]+sum[rson];
}
void build(int id, int l, int r) {
cnt[id] = sum[id] = 0;
if (l == r) return ;
build(lson,l,mid);
build(rson,mid+1,r);
push_up(id);
}
void update(int pos, LL C, int l, int r, int id) {
if (l == r && l == pos) {
cnt[id] += C;
sum[id] += C*l;
return ;
}
if (pos <= mid) {
update(pos,C,l,mid,lson);
} else {
update(pos,C,mid+1,r,rson);
}
push_up(id);
}
LL query(LL C, int l, int r, int id) {
if (l == r) return C*l;
if (cnt[lson] >= C) {
return query(C,l,mid,lson);
} else {
return sum[lson]+query(C-cnt[lson],mid+1,r,rson);
}
}
int main() {
#ifndef ONLINE_JUDGE
int startTime = clock();
FRD;
#endif
while (~scanf("%d", &n)) {
LL tot_sum = 0, ans = 1e18;
for (int i = 1; i <= n; i++) {
scanf("%lld%lld%lld", &A[i].h,&A[i].c,&A[i].p);
tot_sum += 1ll*A[i].c*A[i].p;
}
sort(A+1,A+n+1);
build(1,1,200);
LL pre_num = 0, pre_sum = 0;
for (int l = 1; l <= n; l++) {
int r = l;
LL now_num = 0;
while (r<=n&&A[l].h==A[r].h) {
pre_sum += A[r].c*A[r].p;
now_num += A[r].p;
r++;
}
if (pre_num >= now_num) {
LL del_num = pre_num-now_num+1;
LL del_sum = query(del_num,1,200,1);
my_min(ans,tot_sum-pre_sum+del_sum);
} else {
my_min(ans,tot_sum-pre_sum);
}
for (int i = l; i < r; i++) {
update(A[i].c,A[i].p,1,200,1);
}
pre_num += now_num;
l = r-1;
}
printf("%lld\n", ans);
}
#ifndef ONLINE_JUDGE
printf("Time = %dms\n", clock() - startTime);
#endif
return 0;
}
总结:其实和线段树一个意思,就是表示的意思不一样。