想复杂了?感觉是大模拟,纯模拟出来了。
#include <iostream> #include <queue> #include <map> #include <set> #include <cmath> #include <cstring> #include <algorithm> #include <iomanip> #include <stack> #include <numeric> #include <ctime> #include <string> #include <bitset> #include <unordered_map> #include <unordered_set> using namespace std; using ll = long long; const ll N = 1e5 + 5, mod = 1e9 + 7, inf = 0x3f3f3f3f; void solve() { string a; cin >> a; int ans = 0, sum = 0; map<char, int>mp; for (int i = 0; i < a.size(); i++) { sum += (a[i] - '0'); if (a[i] == '3' || a[i] == '6' || a[i] == '9')a[i] = '3'; else a[i] = (a[i] - '0') % 3 + '0'; if (a[i] == '3' || a[i] == '0')ans++; mp[a[i]]++; //cout<<a[i]; } if (sum % 3) { if (sum % 3 == 1) { if (mp['1']) { if (mp['1'] == 1) { for (int i = 0; i < a.size(); i++) { if (a[i] == '1') { while (i + 1 < a.size() && a[i + 1] == '0') { i++; ans--; } break; } } } cout << (ans == 0 ? 0 : ans + 1) << '\n'; return ; } else { cout << 0 << '\n'; return ; } } else if (sum % 3 == 2) { if (mp['2']) { if (mp['2'] == 1) { for (int i = 0; i < a.size(); i++) { if (a[i] == '2') { while (i + 1 != a.size() && a[i + 1] == '0') { i++; ans--; } break; } } } cout << (ans == 0 ? 0 : ans + 1) << '\n'; return ; } else { cout << 0 << '\n'; return ; } } } else { if (ans == a.size()) { cout << ans - 1 << '\n'; return ; } else { cout << ans << '\n'; return ; } } } int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t = 1; cin >> t; while (t--) { solve(); } return 0; }