0 s, 1 s and ? Marks |
Given a string consisting of 0, 1 and ? only, change all the ? to 0/1, so that the size of the largest group is minimized. A group is a substring that contains either all zeros or all ones.
Consider the following example:
0 1 1 ? 0 1 0 ? ? ?
We can replace the question marks (?) to get
0 1 1 0 0 1 0 1 0 0
The groups are (0) (1 1) (0 0) (1) (0) (1) (0 0) and the corresponding sizes are 1, 2, 2, 1, 1, 1, 2. That means the above replacement would give us a maximum group size of 2. In fact, of all the 24 possible replacements, we won't get any maximum group size that is smaller than 2.
The first line of input is an integer T ( T5000) that indicates the number of test cases. Each case is a line consisting of a string that contains 0, 1 and ? only. The length of the string will be in the range [1,1000].
4 011?010??? ??? 000111 00000000000000
Case 1: 2 Case 2: 1 Case 3: 3 Case 4: 14
最大值最小,二分。关键是已知最大长度,怎么判断是否可行。贪心+分类讨论,各种yy就可以了,这题还是比较简单的。
#include <cstdio> #include <algorithm> #include <vector> #include <map> #include <queue> #include <iostream> #include <stack> #include <set> #include <cstring> #include <stdlib.h> #include <cmath> using namespace std; typedef long long LL; typedef pair<int, int> P; const int maxn = 500 + 5; vector<P> v; int n, from, to; string s; bool judge(int x){ int sum = 1, last_pos = from, total = 0; for(int i = from+1;i <= to;i++){ if(s[i] == '?'){ total++; } else{ if(total == 0){ if(s[i] == s[i-1]) sum++; else sum = 1; } else if(total == 1){ if(s[i] == s[last_pos]){ sum = 1; } else{ if(sum + 1 <= x){ sum = 1; } else{ sum = 2; } } } else{ if(s[i] == s[last_pos]){ if(total%2 == 0 && x < 2){ return false; } } else{ if(total%2 == 1 && x < 2){ return false; } } sum = 1; } last_pos = i; total = 0; } if(sum > x) return false; } return true; } int main(){ int t, kase = 0; scanf("%d", &t); while(t--){ kase++; cin >> s; n = s.length(); from = n, to = -1; for(int i = 0;i < n;i++){ if(s[i] != '?'){ from = i; break; } } for(int i = n-1;i >= 0;i--){ if(s[i] != '?'){ to = i; break; } } int l = 1, r = n+1; int ans = 1; while(l <= r){ int mid = (l+r) / 2; if(judge(mid)){ r = mid-1; ans = mid; } else{ l = mid+1; } } printf("Case %d: %d\n", kase, ans); } return 0; }