PAT (Advanced Level) 1044. Shopping in Mars (25)

双指针。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;

const int maxn=100000+10;
long long a[maxn];
int n; long long val,Min;
struct Ans
{
    int L,R;
    Ans(int a,int b)
    {
        L=a;
        R=b;
    }
};
vector<Ans>v;

int main()
{
    Min=9999999999999;
    scanf("%d%lld",&n,&val);
    for(int i=1;i<=n;i++) scanf("%lld",&a[i]);

    long long sum=a[1];
    int p1=1,p2=1;
    while(1)
    {
        int fail=1;
        if(sum>=val)
        {
            if(sum-val<Min)
            {
                Min=sum-val;
                v.clear();
                v.push_back(Ans(p1,p2));
            }
            else if(sum-val==Min)
                v.push_back(Ans(p1,p2));
            if(p1<=n)
            {
                sum=sum-a[p1];
                p1++;
                fail=0;
            }
        }
        else
        {
            if(p2+1<=n){
                p2++;
                sum=sum+a[p2];
                fail=0;
            }
        }
        if(fail==1) break;
    }

    for(int i=0;i<v.size();i++)
    {
        printf("%d-%d\n",v[i].L,v[i].R);
    }
    return 0;
}

 

posted @ 2016-05-25 14:37  Fighting_Heart  阅读(192)  评论(0编辑  收藏  举报