Advertisement
welleyth

F. Довідки 25/25

Apr 11th, 2021
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define int long long
  4. #define pb push_back
  5. #define mp make_pair
  6. //#define ull long long
  7.  
  8. typedef unsigned long long ull;
  9.  
  10. using namespace std;
  11.  
  12. const int DEBUG = 0;
  13. const int INF = ((int)1e15 + 10);
  14. const int N = 100010;
  15. const int md = (int)1e7 + 19;
  16.  
  17.  
  18. int n,k;
  19. int l[N],r[N];
  20. int ans = 0;
  21.  
  22. vector<int> d(N);
  23. vector<vector<int> > g(N);
  24.  
  25. void dfs(int v,int cur = 0,int counter = 1)
  26. {
  27.     if(counter == k)
  28.     {
  29.         ans = max(ans,cur);
  30.         return;
  31.     }
  32.     if(abs(l[v]-v) > abs(r[v] - v))
  33.         dfs(l[v],cur + abs(l[v]-v),counter+1);
  34.     else
  35.         dfs(r[v],cur + abs(r[v]-v),counter+1);
  36.  
  37.     return;
  38. }
  39.  
  40. signed main()
  41. {
  42.     ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  43.  
  44.     cin >> n >> k;
  45.  
  46.     vector<int> a(n);
  47.  
  48.     for(int i = 0; i < n; i++)
  49.         cin >> a[i];
  50.  
  51.     vector<int> pos(k+1,-1);
  52.     vector<int> start;
  53.  
  54.     for(int i = 0; i < n; i++)
  55.     {
  56.         if(a[i] == 1)
  57.             start.pb(i);
  58.         if(pos[a[i]] == -1)
  59.             pos[a[i]] = i;
  60.         if(pos[a[i]+1] == -1)
  61.             l[i] = i;
  62.         else
  63.             l[i] = pos[a[i]+1];
  64.     }
  65.  
  66.     pos.assign(k+1,-1);
  67.  
  68.     for(int i = n - 1; i >= 0; i--)
  69.     {
  70.         if(pos[a[i]] == -1)
  71.             pos[a[i]] = i;
  72.         if(pos[a[i]+1] == -1)
  73.             r[i] = i;
  74.         else
  75.             r[i] = pos[a[i]+1];
  76.     }
  77.  
  78.     for(auto x : start)
  79.         dfs(x);
  80.  
  81.     if(n <= 5000)
  82.     {
  83.         for(int i = 0; i < n; i++)
  84.             g[a[i]].pb(i);
  85.         queue<int> q;
  86.         for(auto x : start)
  87.             q.push(x);
  88.         int v;
  89.         while(!q.empty())
  90.         {
  91.             v = q.front();
  92.             q.pop();
  93.             for(auto x : g[a[v]+1])
  94.             {
  95.                 if(d[x] < d[v] + abs(v-x))
  96.                 {
  97.                     d[x] = d[v] + abs(v-x);
  98.                     q.push(x);
  99.                 }
  100.             }
  101.         }
  102.         for(auto x : g[k])
  103.             ans = max(ans,d[x]);
  104.     }
  105.  
  106.     cout << ans;
  107.  
  108.     return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement