题目大意:变换字符串直到符合题目要求,求最小的变化次数
解题思路:贪心,每次遇到不满足的就变化
参考代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n;
string s;
int main() {
cin >> n;
while (n--) {
cin >> s;
int ans = 0;
if (s == "^") ans++;
if (s[0] == '_')ans++;
if (s.back() == '_') ans++;
int cnt = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '_') {
cnt++;
if (cnt > 1) ans++, cnt = 0, i--, s[i] = '^';
} else {
cnt = 0;
}
}
cout << ans << endl;
}
return 0;
}
B JoJo's Incredible Adventures
题目大意:给定01串,通过特定规则变化为01矩阵,求由1构成的最大矩形面积
解题思路:找规律,分类讨论
参考代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e3 + 5;
int n;
string s;
int main() {
cin >> n;
while (n--) {
cin >> s;
ll x = s.size();
ll n1 = 0, n0 = 0;
for (int i = 0; i < x; i++) {
if (s[i] == '0') n0++;
else n1++;
}
if (n1 == 0) {
cout << 0 << endl;
continue;
}
if (n1 == x) {
cout << x*x << endl;
continue;
}
s += s;//成环
ll ans = 0;
ll res = 0;//最大连续1的个数
for (int i = 0; i < s.size(); i++) {
if (s[i] == '1') ans++;
else ans = 0;
res = max(res, ans);
}
if (res % 2 == 0) {
ans = (res / 2) * (res / 2 + 1);
cout << ans << endl;
} else {
ans = (res / 2 + 1) * (res / 2 + 1);
cout << ans << endl;
}
}
return 0;
}
题目大意:给定长度为n的数列,定义mex(),问是否能进行一次区间赋值,使mex()的值+1
解题思路:要使mex()的值+1,则必须保证数列中不存在mex()这个值,找出最两端的数值为mex()的下标,把中间的全部修改,再统计mex()是否+1即可。
参考代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e5 + 5;
ll T, n;
ll a[N];
unordered_map<ll, int>mp;
ll mex() {
mp.clear();
for (int i = 1; i <= n; i++) {
mp[a[i]]++;
}
for (ll i = 0;; i++) {
if (mp[i] == 0) return i;
}
}
int main() {
cin >> T;
while (T--) {
cin >> n;
a[n + 1] = -1;
for (int i = 1; i <= n; i++) cin >> a[i];
int m = mex();
if (m == 0) {
cout << "Yes" << endl;
continue;
}
if (n == 1) {
cout << "No" << endl;
continue;
}
if (m + 1 > n) {
cout << "No" << endl;
continue;
}
int l = -1, r = -1;
for (int i = 1; i <= n; i++) {
if (a[i] == m + 1) {
l = i;
break;
}
}
for (int i = n; i >= 1; i--) {
if (a[i] == m + 1) {
r = i;
break;
}
}
if (l == -1 && r == -1) {
cout << "Yes" << endl;
continue;
}
for (int i = l; i <= r; i++) {
mp[a[i]]--;
}
int t = 1;
for (int i = 0; i < m; i++) {
if (mp[i] == 0) {
cout << "No" << endl;
t = 0;
break;
}
}
if (t) cout << "Yes" << endl;
}
return 0;
}
D
E
F