PAT 顶级 1026 String of Colorful Beads (35分)(尺取法)
题目链接:
1026 String of Colorful Beads
思路:
采用尺取法的思想,每次推动首尾,寻找最长、价值最大的区间即可;
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 12345;
int n, val[maxn], type[maxn];
bool vst[maxn];
int main(){
// freopen("Sakura.txt", "r", stdin);
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", val + i);
for(int i = 0; i < n; i++) scanf("%d", type + i);
int lf, rt, len = 0, v = 0;
int p = 0, q = 0, nowv = 0;
while(true){
while(vst[type[q]] == false && q < n) vst[type[q]] = true, nowv += val[type[q]], q++;
// cerr<< p << ' ' << q << '\n';
int nowlen = q - p;
if(nowlen > len || (nowlen == len && nowv > v)){
lf = p, rt = q - 1, len = nowlen, v = nowv;
}
if(q >= n) break;
while(vst[type[p]] = false, nowv -= val[type[p]], type[p++] != type[q]);
}
printf("%d %d %d\n", v, lf, rt);
return 0;
}