Beingamanforever

subarray with zero sum

Dec 25th, 2024
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-12-25 23:37:48
  4.  **/
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  8. #define NeedForSpeed                  \
  9.     ios_base::sync_with_stdio(false); \
  10.     cin.tie(NULL);                    \
  11.     cout.tie(NULL);
  12. #define int long long
  13. #define all(x) (x).begin(), (x).end()
  14. typedef vector<int> vi;
  15. typedef vector<bool> vb;
  16. typedef vector<vi> vvi;
  17. typedef vector<pair<int, int>> vpi;
  18. #define f first
  19. #define s second
  20. #define yes cout << "YES" << endl
  21. #define no cout << "NO" << endl
  22. #define endl "\n"
  23. const int mod = 1000000007;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. void solve()
  26. {
  27.     // subarray with sum 0, minimum size
  28.     int n;
  29.     cin >> n;
  30.     string s;
  31.     cin >> s;
  32.     map<pair<int, int>, int> mp;
  33.     mp[{0, 0}] = 0;
  34.     int hor = 0, ver = 0, start = -1, end = -1, min_len = LLONG_MAX;
  35.     for (int i = 0; i < n; i++)
  36.     {
  37.         if (s[i] == 'L')
  38.         {
  39.             hor--;
  40.         }
  41.         else if (s[i] == 'R')
  42.         {
  43.             hor++;
  44.         }
  45.         else if (s[i] == 'U')
  46.         {
  47.             ver++;
  48.         }
  49.         else if (s[i] == 'D')
  50.         {
  51.             ver--;
  52.         }
  53.         // if they have same value of hor, ver means in b/w we have a subarray with sum 0
  54.         if (mp.count({hor, ver}))
  55.         {
  56.             int prev_index = mp[{hor, ver}];
  57.             if (i - prev_index < min_len)
  58.             {
  59.                 min_len = i - prev_index;
  60.                 start = prev_index + 1;
  61.                 end = i + 1;
  62.             }
  63.         }
  64.         mp[{hor, ver}] = i + 1;
  65.     }
  66.     if (start == -1)
  67.     {
  68.         cout << -1 << endl;
  69.     }
  70.     else
  71.     {
  72.         cout << start << " " << end << endl;
  73.     }
  74.     return;
  75. }
  76.  
  77. signed main()
  78. {
  79.     NeedForSpeed;
  80.     int t = 1;
  81.     cin >> t;
  82.     while (t--)
  83.     {
  84.         solve();
  85.     }
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment