PAT (Advanced Level) 1044 Shopping in Mars

Posted vividbingo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1044 Shopping in Mars相关的知识,希望对你有一定的参考价值。

题解

  利用前缀和维护钻石的价值,然后枚举左端点,二分查找右端点。

代码

#include<bits/stdc++.h>
using namespace std;
int n,m,pre_sum[100005];
vector<int> ans;
void check(int i,int &j,int &check);
int main()
{
    int i,j,mmin,result;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&pre_sum[i]);
        pre_sum[i]+=pre_sum[i-1];
    }
    for(i=1,mmin=pre_sum[n];i<=n;i++)
    {
        check(i,j,result);
        if(result>mmin) continue;
        if(result>=m)
        {
            if(result<mmin)
            {
                ans.clear();
                mmin=result;
            }
            ans.push_back(i);
            ans.push_back(j);
        } 
    }
    for(i=0;i<ans.size()-1;i+=2)
        printf("%d-%d
",ans[i],ans[i+1]);
    system("pause");
    return 0;
}
void check(int i,int &j,int &result)
{
    int left=i,right=n,mid;
    while(left<=right)
    {
        mid=(left+right)/2;
        if(pre_sum[mid]-pre_sum[i-1]>=m) j=mid,right=mid-1;
        else left=mid+1;
    }
    result=pre_sum[j]-pre_sum[i-1];
}

以上是关于PAT (Advanced Level) 1044 Shopping in Mars的主要内容,如果未能解决你的问题,请参考以下文章

PTA(Advanced Level)1044.Shopping in Mars

PAT (Advanced Level) 1025. PAT Ranking (25)

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095

PAT Advanced Level 1038