CodeForce-812C Sagheer and Nubian Market(二分)

Sagheer and Nubian Market

CodeForces - 812C

题意:n个货物,每个货物基础价格是ai。
当你一共购买k个货物时,每个货物的价格为a[i]+k*i。
每个货物只能购买一次。给你s金币,问你最多可以购买多少个货物,这些货物的最小花费。
题解:
直接二分(1~n)购买数量,每次二分都对每个货物计算价格a[i]+mid*i。
结构体对价格排序,mid个货物总价格大于s的时候break并往小二分,否则往大二分。
数据类型开long long。
#include <cstdio>  
#include <iostream>  
#include <cmath>  
#include <algorithm>  
#include <string>  
#include <cstring>  
// #define _ ios::sync_with_stdio(false) 
// #define cin.tie(0)
#define PI 3.141592653
using namespace std;
// #define rep(i,x,y) for(int i=x;i<y;i++)
const int INF = 10000000;
const int MAXN = 200050;
typedef long long ll;

struct st
{
    ll id;
    ll val;
    ll sum;
}a[100050];
bool cmp(st a,st b)
{
    return a.sum<b.sum;
}
int main()
{
    int n;
    ll s;
    cin>>n>>s;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i].val;
        a[i].id=i;
    }
    int result=0;
    ll t=0;
    int low=0,high=n;
    while(low<=high)
    {
        int mid=(low+high)/2;
        for(int i=1;i<=n;i++)
        {
            a[i].sum=a[i].val+a[i].id*mid;
        }
        ll sm=0;
        sort(a+1,a+1+n,cmp);
        for(int i=1;i<=mid;i++)
        {
            sm+=a[i].sum;
            if(sm>s)
            {break;}
        }
        if(sm<=s)
        {
            result=mid;
            t=sm;
            low=mid+1;
        }
        else 
            high=mid-1;
    }
    cout<<result<<" "<<t<<endl;
    return 0;
}   
原文地址:https://www.cnblogs.com/YingZhixin/p/7133149.html