题解:AT_abc116_d [ABC116D] Various Sushi

· · 题解

AT_abc116_d [ABC116D] Various Sushi

传送门

题目大意

给定一个长度为 N 的数列,其中每个数都有一个权值 d_i 和一个种类 t_i。现在其中选 K 个数,求贡献最大值。

其中贡献 S 的计算为所选数的权值之和加种类数的平方。

题目分析

我们要同时考虑权值和种类,这太繁琐了。我们不妨先忽略种类,而只考虑权值。

很显然,只考虑权值时只需将数列依照权值降序排序,选前 K 个数即可

现在,我们在考虑种类对于贡献的影响。因为相同的种类只计算一次,又因为我们开始时选的是最优的,所以为了让贡献最大,往后枚举时,已有的就不必再选,因为这时种类不变而权值和减小。同理,被替换掉的也一定是出现多次的。

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=2e5+10;
int n,m,f[N];//f为出现次数
struct node{
    int t,k;
}a[N];//数列
bool cmp(node z,node x){
    return z.t>x.t;
}
signed main(){
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        cin>>a[i].k>>a[i].t;
//输入
    sort(a+1,a+1+n,cmp);//排序
    int res=0,tot=0,cnt=0;
    for(int i=1;i<=m;i++){
        if(f[a[i].k]==0) cnt++;
        f[a[i].k]++;
        tot+=a[i].t;
    }//向后枚举答案
    res=tot+cnt*cnt;
    int w=m;
    for(int i=m+1;i<=n;i++){
        if(w==0) break;
        if(f[a[i].k]!=0) continue;
        f[a[i].k]++;
        tot+=a[i].t;
        while(f[a[w].k]<=1&&w!=0)
            w--;
        if(w==0) break;
        f[a[w].k]--;
        cnt++;
        tot-=a[w].t;
        w--;
        res=max(res,tot+cnt*cnt);
    }
    cout<<res;
    return 0;
}