# | Submission time | Handle | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
283179 | 2020-08-25T10:58:23 Z | MohamedAhmed04 | Ancient Books (IOI17_books) | C++14 | 0 ms | 0 KB |
#include <bits/stdc++.h> #include "books.h" #include "grader.cpp" using namespace std ; const int MAX = 1e6 + 10 ; int n ; int to[MAX] ; int vis[MAX] ; long long cost[MAX] ; long long dfs(int node) { if(vis[node]) return 0ll ; vis[node] = 1 ; return (dfs(to[node]) + abs(to[node] - node)) ; } long long minimum_walk(std::vector<int> p, int s) { n = p.size() ; for(int i = 0 ; i < n ; ++i) to[i] = p[i] ; for(int i = 0 ; i < n ; ++i) { if(vis[i]) continue ; cost[i] = dfs(i) ; } long long ans = 0 ; for(int i = 0 ; i < n ; ++i) ans += cost[i] ; for(int i = n-1 ; i >= 0 ; --i) { if(cost[i]) ans += i * 2ll ; } return ans ; }