最优解代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int ans, f, c1;
char s[N];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> s + 1;
for (int i = 1, j = 0; s[i]; i++)
if (s[i] == '0' && s[i - 1] == '0')
ans += f ? 1 : c1, j = c1 = f = 0;
else {
int t = s[i] - s[i - 1];
f |= t > 0 && j < 0;
j = t;
c1 += s[i] == '1';
}
cout << ans + (f ? 1 : c1);
return 0;
}
最劣解代码:
#include <bits/stdc++.h>
using namespace std;
int ans, f, c1;
int main() {
for (int x, p = -1, t = 0; scanf("%1d", &x) == 1; p = x)
if (!x && !p) ans += f ? 1 : c1, t = c1 = f = 0;
else {
int d = x - p;
f |= d > 0 && t < 0;
t = d;
c1 += x;
}
cout << ans + (f ? 1 : c1);
return 0;
}
两个代码算法是一样的,本来想用scanf优化掉数组,看看是不是能更快一点,结果提交变成了最劣解……不知道是怎么回事!