PAT (Advanced Level) 1044 Shopping in Mars

题解

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

代码

#include
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;i1;i+=2)
        printf("%d-%d\n",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)