Home PAT 1044 Shopping in Mars
Post
Cancel

PAT 1044 Shopping in Mars

Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int n,m,cur;
int d[100010];
vector<pair<int,int>>ans;
int main() {
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i){
        scanf("%d",&d[i]);
        d[i]+=d[i-1];
    }
    cur=1000000000;
    bool flag=false;
    int i=1,j=1;
    while(i<=j&&j<=n){
        int temp=d[j]-d[i-1];
        if(temp==m){
            if(!flag){
                flag=true;
                ans.clear();
            }
            ans.push_back({i,j});
            i++,j++;
        }else if(temp<m) j++;
        else{
            if(!flag){
                if(cur>temp-m){
                    cur=temp-m;
                    ans.clear();
                    ans.push_back({i,j});
                }else if(cur==temp-m)
                    ans.push_back({i,j});
            }
            //注意这里需要判断, 不能只 i++, 否则当 i==j 时 i++ 就会导致 i>j 从而退出循环, 后面的序列就没有被遍历到.
            if(i<j) i++;
            else i++,j++;
        }
    }
    for(i=0;i<ans.size();++i)
        printf("%d-%d\n",ans[i].first,ans[i].second);
    return 0;
}
This post is licensed under CC BY 4.0 by the author.