BZOJ2217 [Poi2011]Lollipop 【贪心】
题目链接
题解
如果只判定存不存在方案的话,我倒是想到可以将\(2\)拆成两个\(1\),其中一个不能作为区间开头,线段树优化计算补集方案数
但是一看这道题要输出方案啊,,,
怎么办?
考虑如果凑不出\(x\),那一定可以凑出\(x + 1\)
我们就找到前缀和为\(x\)的位置,如果没有,就找\(x + 1\)
前缀和为\(x\)当然就得到答案啦
前缀和为\(x + 1\),我们考虑将区间整体右移,如果左端点出去和右端点进来的数相同,区间值不变,如果不同,那我们就可以通过调整使得区间的值减少\(1\)
贪心预处理一下答案即可
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
#define lbt(x) (x & -x)
using namespace std;
const int maxn = 1000005,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int ansl[maxn << 1],ansr[maxn << 1],sum[maxn],R[maxn],n,m,N;
char S[maxn];
int main(){
n = read(); m = read();
scanf("%s",S + 1);
REP(i,n) sum[i] = sum[i - 1] + (S[i] == 'W' ? 1 : 2);
for (int i = n - 1; ~i; i--){
if (sum[i + 1] - sum[i] == 2) R[i] = R[i + 1] + 1;
else R[i] = 0;
}
//REP(i,n + 1) printf("R[%d] = %d\n",i - 1,R[i - 1]);
int pos = 1;
for (int i = 1; i <= sum[n]; i++){
while (sum[pos] != i && sum[pos] != i + 1) pos++;
if (sum[pos] == i) ansl[i] = 1,ansr[i] = pos;
else {
if (R[0] == R[pos]){
ansl[i] = R[0] + 2,ansr[i] = pos + R[pos];
}
else if (R[0] < R[pos]) ansl[i] = R[0] + 2,ansr[i] = pos + R[0];
else if (pos + R[pos] < n) ansl[i] = R[pos] + 2,ansr[i] = pos + R[pos] + 1;
}
}
int len;
while (m--){
len = read();
if (!ansl[len] || ansl[len] > ansr[len]) puts("NIE");
else printf("%d %d\n",ansl[len],ansr[len]);
}
return 0;
}