Zero-Sum Ranges ã®å¿ç¨åé¡ã ãã©ãæåé£ããèãã¦ãã¾ã£ã¦ã解ããªã...ãã¨ãªã£ã¦ã¾ãã
é¡é¡ã¨ã
åé¡æ¦è¦
"J" 㨠"O" 㨠"I" ã®ã¿ãããªãé·ã ã®æåå ãä¸ããããã ã®é£ç¶ããé¨åæååã§ãã£ã¦ãããã«å«ã¾ãã "J" ã®åæ°ã¨ã"O" ã®åæ°ã¨ã"I" ã®åæ°ããã¹ã¦äºãã«çãããããªãã®ãèããã
ãã®ãããªé¨åæååã®é·ãã®æ大å¤ãæ±ããã
å¶ç´
èãããã¨
ç´¯ç©åã使ãã°ã ã¾ã§ã¯èªæãªã®ã ãã©ãããããå ãããã«ã¯ããããªãã£ããå¤åãå¹³æ¹åå²ã¨ããããããé£ã³éå ·ã使ãæãã§ã¯ãªãã®ã ãããã©ã...
ããããã¨ãã¯ãæåã®ç¨®é¡ãå°ãªãã±ã¼ã¹ããèããã¨åãªãã¨ãããã¨æããã¨ããããã§ã"J" 㨠"O" 㨠"I" ã® 3 æåã§ã¯ãªãã"A" 㨠"B" ã® 2 æåã ãã®å ´åãèãã¦ã¿ããã¨ã«ããã
2 æåã ãã®å ´å
ãã®å ´åã¯èããããã次ã®é åãèããã
- P[ i ] := æåã® i æåã«ã¤ãã¦ã®ã(A ã®åæ°) - (B ã®åæ°)
ãã®ã¨ãã
ãåºé [l, r) ãæ¡ä»¶ãæºããããâã P[ l ] = P[ r ]
ãæãç«ã¤ã®ã ããã¨ã¯ Zero-Sum Ranges ã¨ã¾ã£ããåãèãæ¹ã§è§£ãããã¾ã P ã®å¤ã§å index (0, 1, ..., N) ãåé¡ãã¦ããããããã¦ã次ã®ããã«è§£ããã
- åå¤ v ã«å¯¾ãã¦
- P[ i ] = v ã¨ãªãæ大㮠i ã Mãæå°ã® i ã m ã¨ãã¦
- M - m ã®æ大å¤ãæ±ãã
3 æåã«ãªã£ãå ´å
2 æåã®å ´åã¨ã»ã¨ãã©åæ§ã«è§£ããã
- P[ i ] := æåã® i æåã«ã¤ãã¦ã®ã("O" ã®åæ°) - ("J" ã®åæ°)
- Q[ i ] := æåã® i æåã«ã¤ãã¦ã®ã("I" ã®åæ°) - ("J" ã®åæ°)
ã¨ããããã®ã¨ã
ãåºé [l, r) ãæ¡ä»¶ãæºããããâã P[ l ] = P[ r ] ã㤠Q[ l ] = Q[ r ]
ã¨ãªãï¼ï¼ï¼ããã£ã¦ã(P ã®å¤, Q ã®å¤) ã®ãã¢ã§å index (0, 1, ..., N) ãåé¡ãã¦ãããã°ããããã¨ãã° map ãç¨ãããã¨ã«ããã¨ãè¨ç®é㯠ã¨ãªãã
ã³ã¼ã
#include <bits/stdc++.h> using namespace std; int main() { int N; string S; cin >> N >> S; long long a = 0, b = 0, c = 0; using pll = pair<long long, long long>; map<pll, vector<int>> ma; ma[pll(0, 0)].push_back(0); for (int i = 0; i < N; ++i) { if (S[i] == 'J') ++a; else if (S[i] == 'O') ++b; else ++c; ma[pll(b-a, c-a)].push_back(i+1); } int res = 0; for (auto it : ma) { auto v = it.second; if (v.size() < 2) continue; res = max(res, v.back() - v[0]); } cout << res << endl; }