Advertisement
Dang_Quan_10_Tin

PARENTHESES TS10 PTNK 2020-2021

Jan 5th, 2022
739
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #define task "PARENTHESES"
  2.  
  3. #include <iostream>
  4. #include <cstdio>
  5.  
  6. using namespace std;
  7.  
  8. using ll = long long;
  9. using ld = long double;
  10.  
  11. constexpr int N = 1e6 + 5;
  12. constexpr int Inf = 1e9 + 7;
  13. int n;
  14. string s;
  15. int b[N];
  16. int pref[N], suf[N];
  17.  
  18. void Read()
  19. {
  20.     cin >> s;
  21.     n = s.size();
  22.  
  23.     for (int i = 1; i <= n; ++i)
  24.         b[i] = b[i - 1] + (s[i - 1] == '(' ? 1 : -1);
  25. }
  26.  
  27. void Solve()
  28. {
  29.     if (b[n] != 0) // Không thể tạo ra dãy ngoặc đúng
  30.     {
  31.         cout << -1;
  32.         return;
  33.     }
  34.  
  35.     pref[0] = suf[n + 1] = Inf;
  36.  
  37.     for (int i = 1; i <= n; ++i)
  38.         pref[i] = min(pref[i - 1], b[i]);
  39.     for (int i = n; i; --i)
  40.         suf[i] = min(suf[i + 1], b[i]);
  41.  
  42.     for (int i = 0; i < n; ++i)
  43.         if (pref[i] >= b[i] - b[n] && suf[i + 1] >= b[i]) // Tìm thấy cách tạo dãy ngoặc đúng
  44.         {
  45.             cout << i;
  46.             return;
  47.         }
  48. }
  49.  
  50. int32_t main()
  51. {
  52.     ios::sync_with_stdio(0);
  53.     cin.tie(0);
  54.     cout.tie(0);
  55.     if (fopen(task ".INP", "r"))
  56.     {
  57.         freopen(task ".INP", "r", stdin);
  58.         freopen(task ".OUT", "w", stdout);
  59.     }
  60.  
  61.     Read();
  62.     Solve();
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement