Beingamanforever

Divide and Conquer, Optimized O(n^2)

Feb 3rd, 2025
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. // Given an array arr[] consisting of N integers, the task is to check if all subarrays of the array
  2. // have at least one unique element in it or not. If found to be true, then print “Yes”.else  print “No”.
  3. // https://www.geeksforgeeks.org/check-if-all-subarrays-contains-at-least-one-unique-element/
  4. #include <bits/stdc++.h>
  5. // #include <atcoder/all>
  6. using namespace std;
  7. #define int long long
  8. #define all(x) (x).begin(), (x).end()
  9. typedef vector<int> vi;
  10. typedef vector<vi> vvi;
  11. typedef vector<pair<int, int>> vpi;
  12. typedef pair<int, int> pi;
  13. #define f first
  14. #define s second
  15. #define pb push_back
  16. #define endl "\n"
  17. #define yes cout << "YES" << endl
  18. #define no cout << "NO" << endl
  19. int dx[] = {-1, 0, 1, 0};
  20. int dy[] = {0, 1, 0, -1};
  21. const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
  22. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  23. // -----------------------------------------------------------------------------
  24. vi a;
  25. bool solve(int l, int r)
  26. {
  27.     if (l >= r)
  28.     {
  29.         return true;
  30.     }
  31.     map<int, int> mpp;
  32.     for (int i = l; i <= r; i++)
  33.     {
  34.         mpp[a[i]]++;
  35.     }
  36.     // am1, am2, am3,..., amn -> unique elements, divide & conquer in each range
  37.     int last = l;
  38.     bool unique = false;
  39.     for (int i = l; i <= r; i++)
  40.     {
  41.         if (mpp[a[i]] == 1)
  42.         {
  43.             unique = true;
  44.             if (!solve(last, i - 1))
  45.             {
  46.                 return false;
  47.             }
  48.             last = i + 1;
  49.         }
  50.     }
  51.     return (unique && (solve(last, r)));
  52. }
  53. void solve()
  54. {
  55.     int n;
  56.     cin >> n;
  57.     a.resize(n);
  58.     for (int i = 0; i < n; i++)
  59.     {
  60.         cin >> a[i];
  61.     }
  62.     if (solve(0, n - 1))
  63.     {
  64.         yes;
  65.         return;
  66.     }
  67.     no;
  68.     return;
  69. }
  70.  
  71. signed main()
  72. {
  73.     // __START__;
  74.     ios_base::sync_with_stdio(false);
  75.     cin.tie(NULL);
  76.     cout.tie(NULL);
  77.     int t = 1;
  78.     // cin >> t;
  79.     while (t--)
  80.     {
  81.         solve();
  82.     }
  83.     // __END__;
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment