codeforces 814C(二分)
题目链接:http://codeforces.com/contest/814/problem/C
题意:给出一个字符串和一个字符,最多可以改k次,问全为该字符的子序列最长为多少。
思路:sum[char][i]表示字符串前i项中有多少个字符不为该字符,枚举l,二分求r,复杂度O(26*n2*logn)
#include<bits/stdc++.h> using namespace std; typedef long long ll; char a[1505]; int sum[30][1505],ans[30][1505]; int main() { int n,q,x; char c; scanf("%d",&n); scanf("%s",a+1); scanf("%d",&q); for(int i = 1; i <= 26; i++) { for(int j = 1; j <= n; j++) { if(char(i + 96) != a[j]) sum[i][j] = sum[i][j-1] + 1; else sum[i][j] = sum[i][j-1]; } } for(int i = 1; i <= 26; i++) { for(int j = 1; j <= n; j++) { for(int l = 1; l <= n; l++) { int r = upper_bound(sum[i] + l, sum[i] + n + 1, sum[i][l-1] + j) - sum[i] - 1; ans[i][j] = max(ans[i][j], r - l + 1); } } } while(q--) { scanf("%d %c",&x,&c); printf("%d\n",ans[(int)(c - 96)][x]); } return 0; }