Submission #718757

#TimeUsernameProblemLanguageResultExecution timeMemory
718757Jarif_RahmanAncient Books (IOI17_books)C++17
22 / 100
2064 ms38480 KiB
#include <bits/stdc++.h>
#define pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;

struct dsu{
    int n;
    vector<int> sz, p;
    dsu(int nn){
        n = nn;
        sz.resize(n, 1);
        p.resize(n);
        for(int i = 0; i < n; i++) p[i] = i;
    }
    int get(int x){
        if(p[x] != x) p[x] = get(p[x]);
        return p[x];
    }
    void unite(int a, int b){
        a = get(a), b  = get(b);
        if(a == b) return;
        if(sz[b] > sz[a]) swap(a, b);
        sz[a]+=sz[b];
        sz[b] = 0;
        p[b] = a;
    }
};
 
ll minimum_walk(vector<int> p, int s){
    int n = p.size();
    ll ans = 0;
 
    vector<int> C(n, -1), sz;
    int k = 0;
    for(int i = 0; i < n; i++){
        if(C[i] != -1) continue;
        int x = p[i];
        C[i] = k;
        sz.pb(1);
        ans+=abs(i-x);
        while(x != i){
            C[x] = k;
            sz.back()++;
            ans+=abs(p[x]-x);
            x = p[x];
        }
        k++;
    }

    vector<int> first(k, -1), last(k);
    for(int i = 0; i < n; i++){
        if(first[C[i]] == -1) first[C[i]] = i;
        last[C[i]] = i;
    }

    vector<bool> unnecessary(k, 0);
    for(int i = 0; i < n; i++){
        if(sz[C[i]] > 1 || i == s) break;
        unnecessary[C[i]] = 1;
    }
    for(int i = n-1; i >= 0; i--){
        if(sz[C[i]] > 1 || i == s) break;
        unnecessary[C[i]] = 1;
    }

    dsu ds(k);
    for(int i = 0; i < k; i++) for(int j = i+1; j < k; j++){
        if(unnecessary[i] || unnecessary[j]) continue;
        if(last[i] < first[j] || first[i] > last[j]) continue;
        ds.unite(i, j);
    }

    for(int i = 0; i+1 < n; i++){
        if(unnecessary[C[i]] || unnecessary[C[i+1]]) continue;
        if(ds.get(C[i]) != ds.get(C[i+1])) ds.unite(C[i], C[i+1]), ans+=2;
    }

    return ans;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...