题目链接:https://ac.nowcoder.com/acm/contest/887/C
题意:给出n种树和n个h[i],c[i],p[i]代表每种树的高度,砍掉一棵的花费,树的个数。现在要求砍掉一部分树,使得最高的树的个数大于总树木的一半。
数据范围:1<=n<=1e5,1<=Hi<=1e9,1<=Ci<=200,1<=Pi<=1e9
思路:首先,此题只能枚举每种树的高度让其作为最大值,那么我们可以排序后从低到高来枚举(因为数据1e9所以还有提前离散化一下),对于每次枚举一个高度时我们只需要把比他高的全部树木全部砍掉,并且在比他低的树木中砍掉那些花费最小的,使得当前树木个数大于所有树木的一半。比某棵树的高度高的那些树砍掉可以通过花费后缀和来得到,那么对于比某棵树低的花费怎么得到呢?我们观察到cost的范围是200,所以我们可以把cost当成下标,通过cost数组来记录每种花费的树的个数即可,那么找比某棵树小的那些花费的时候直接从1到200暴力砍掉那些花费小的树。复杂度是O(200*n)。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+5;
ll sum[N],cost[205],h[N],num[N],nsum[N];
int n,m,t;
struct p{
ll sum,cost,h;
}a[N];
vector<pair<ll,ll> >G[N];
int main(){
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
scanf("%lld%lld%lld",&a[i].h,&a[i].cost,&a[i].sum);
sum[i]=num[i]=nsum[i]=cost[i]=0,h[i]=a[i].h,G[i].clear();
}
sort(h+1,h+n+1);
ll tot=unique(h+1,h+n+1)-h-1,total=0;
for(int i=1;i<=n;i++){
a[i].h=lower_bound(h+1,h+tot+1,a[i].h)-h;
sum[a[i].h]+=a[i].cost*a[i].sum;
num[a[i].h]+=a[i].sum;
total+=a[i].sum;
G[a[i].h].push_back(make_pair(a[i].sum,a[i].cost));
}
sum[tot+1]=nsum[tot+1]=0;
for(int i=tot;i>=1;i--)sum[i]+=sum[i+1],nsum[i]+=nsum[i+1]+num[i];
ll ans=1ll<<62;
for(int i=1;i<=tot;i++){
ll ret=total-nsum[i]-num[i]+1,mon=0;
if(ret>0){
for(int j=1;j<=200;j++){
if(ret>=cost[j]){
ret-=cost[j];
mon+=cost[j]*j;
}
else{
mon+=ret*j;
break;
}
}
}
ans=min(ans,sum[i+1]+mon);
int len=G[i].size();
for(int j=0;j<len;j++)cost[G[i][j].second]+=G[i][j].first;
}
printf("%lld\n",ans);
}
return 0;
}