4.2美团笔试题2(树状数组)

在这里插入图片描述

解析:

维护一个sum(一圈下来的和),循环内,每次先把可以整圈的部分算了(除法取模)

不能整圈(sum>m)的情况,显然某个前缀的sum已经>m了,所以我们二分这个前缀(动态前缀和使用树状数组维护),将第一个大于m的前缀的那个位置删掉。

详情看代码:

/*
 *  Author : Jk_Chen
 *    Date : 2020-04-02-20.14.15
 */
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
void test(){cerr<<"\n";}
template<typename T,typename... Args>void test(T x,Args... args){cerr<<x<<" ";test(args...);}
const LL mod=1e9+7;
const int maxn=1e5+9;
const int inf=0x3f3f3f3f;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
    while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
    while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
    if(last=='-')ans=-ans; return ans;
}
#define rd rd()
/*_________________________________________________________begin*/

int n;
LL a[maxn];

LL tr[maxn];
void update(int pos,LL val){
    while(pos<=n){
        tr[pos]+=val;
        pos+=pos&-pos;
    }
}
LL query(int pos){
    LL res=0;
    while(pos>0){
        res+=tr[pos];
        pos-=pos&-pos;
    }
    return res;
}


int main(){
    n=rd;
    LL m=rd;
    LL sum=0,res=n;

    rep(i,1,n){
        a[i]=rd;
        sum+=a[i];
        update(i,a[i]);
    }
    LL ans=0;
    while(res>0&&m){
        LL lun=m/sum;
        m=m%sum;
        ans+=lun*res;
        int l=1,r=n,A=-1;
        while(l<=r){
            int mid=(l+r)>>1;
            if(query(mid)>m)A=mid,r=mid-1;
            else l=mid+1;
        }
        update(A,-a[A]);
        res--;
        sum-=a[A];
        continue;
    }
    printf("%lld\n",ans);
    return 0;
}

/*_________________________________________________________end*/
发布了773 篇原创文章 · 获赞 345 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/105279440
今日推荐