http://codeforces.com/contest/676/problem/C
题意:给你一个长度为n的只有a和b的序列,要你通过小于等于k次变化,让一个具有相同字母的子序列长度最长。
思路:一个贪心的思想,要使得子序列最长,必定是a的连续变化或者是b的连续变化。我们向前移动进行变化,当变化次数大于k时,把前面的数变回原样 记录连续最大值即可。
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <map> #include <set> #include <math.h> #include <queue> using namespace std; using ll = long long; int main() { int n, k; cin >> n >> k; string s; cin >> s; int res = 0; int acount = 0; int bcount = 0; int left = 0; for(int i = 0; i < n; i++) { if (s[i] == 'a') acount++; else bcount++; while (acount > k && bcount > k) { if (s[left] == 'a') acount--; else bcount--; left++; } res = max(res, i - left + 1); } cout << res << endl; }
要有看清问题本质,提出最优解决方案的能力。