Problem:
G - Derangement / 完全順列
Story
Dのひとは順列に関する研究をしている。あるときDのひとは、"完全順列 (Derangement)"という順列のクラスを見つけた。「完全な順列とかなんかかっこいい！！！しかもDからはじまる！！！」と廚二病をこじらせたDのひとは、与えられた順列をすべて完全順列に書き換えてしまおうと考えた。
Problem
長さ
n
の順列
p
=
(p_1
p_2
...
p_n)
が与えられる。
i
番目の要素と
j
番目の要素を入れ替える操作には
(p_i+p_j) \times |i-j|
のコストを要する。このとき、上記の入れ替え操作のみを用いて
p
を完全順列にするために必要な最小のコストを求めよ。
ただし、順列
q
が完全順列であるとは、
1 \leq i \leq n
について、
q_i \neq i
が成り立つことを言う。たとえば、
(5
3
1
2
4)
は完全順列であるが、
(3
2
5
4
1)
は
4
番目の数が
4
なので完全順列ではない。
Input
入力は以下の形式からなる。
n
p_1
p_2
...
p_n
1
行目は順列の長さ
n
を表す整数
1
つからなる。
2
行目は
n
個の整数からなり、
i
番目の整数は順列
p
の
i
番目の要素を表す。それぞれは空白
1
文字で区切られている。
制約:
2 \leq n \leq 100
1 \leq p_i \leq n, i \neq j ⇔ p_i \neq p_j
Output
p
を完全順列に並び替えるための最小コストを
1
行に出力せよ。行の最後では必ず改行を行うこと。
Sample Input 1
5
1 2 3 5 4
Sample Output 1
7
1と2を入れ替えた後、1と3を入れ替えると、(2 3 1 5 4)となり完全順列である。
Sample Input 2
5
5 3 1 2 4
Sample Output 2
0
始めから完全順列である。
Sample Input 3
10
1 3 4 5 6 2 7 8 9 10
Sample Output 3
38

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long int;
using ull = unsigned long long int;
using P = pair<int, int>;
using P3 = pair<int,P>;
using PP = pair<P, P>;
constexpr int INF = 1 << 29;
constexpr ll MOD = ll(1e9+7);
constexpr int di[] = {0, 1, 0, -1};
constexpr int dj[] = {1, 0, -1, 0};
constexpr int di8[] = {0, 1, 1, 1, 0, -1, -1, -1};
constexpr int dj8[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr double EPS = 1e-10;

template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }



template <typename T>
struct MinCostFlow{
    using P =  pair<T, int>;
    const T inf = std::numeric_limits<T>::max();

    struct edge{
        int to, rev;
        T cap, cost;
        edge() = default;
        edge(int to, T cap, T cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {}
    };

    int V;
    vector<vector<edge> > G;
    vector<int> h, dist, prevv, preve;

    MinCostFlow() = default;
    MinCostFlow(int n) : G(n) {}

    void init(int n){
        V = n;
        G.resize(V);
    }

    void add_edge(int from, int to, T cap, T cost){
        G[from].push_back((edge){to, cap, cost, int(G[to].size())});
        G[to].push_back((edge){from, 0, -cost, int(G[from].size())-1});
    }

    // 最小費用流
    int min_cost_flow(int s, int t, T f){
        h.resize(G.size());
        dist.resize(G.size());
        prevv.resize(G.size());
        preve.resize(G.size());
        T res = 0;
        fill(h.begin(), h.end(), 0);
        while(f > 0){
            priority_queue<P, vector<P>, greater<P> > que;
            fill(dist.begin(), dist.end(), inf);
            dist[s] = 0;
            que.push({0,s});
            while(!que.empty()){
                P p = que.top();
                que.pop();
                int v = p.second;
                if(dist[v] < p.first) continue;
                for(int i=0;i<int(G[v].size());i++){
                    auto &e = G[v][i];
                    if(e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]){
                        dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        que.push({dist[e.to], e.to});
                    }
                }
            }
            if(dist[t] == inf){
                return -1;
            }
            for(int v=0; v<G.size(); v++) h[v] += dist[v];
            int d = f;
            for(int v=t; v!=s; v=prevv[v]){
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d*h[t];
            for(int v=t; v!=s; v=prevv[v]){
                auto &e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }
};


int solve(){
    int n;
    cin >> n;
    vector<int> p(n);
    for(int i=0;i<n;i++) cin >> p[i];
    MinCostFlow<int> mf;
    int S = n*2, T = n*2+1;
    mf.init(n*2+2);
    for(int i=0;i<n;i++){
        mf.add_edge(S,i,1,0);
        mf.add_edge(i+n,T,1,0);
        for(int j=0;j<n;j++){
            if(p[i]==j+1) continue;
            mf.add_edge(i,j+n,1,p[i]*abs(i-j));
        }
    }
    cout << mf.min_cost_flow(S,T,n) << endl;
    return 0;
}

int main(){
    solve();
    // while(!solve());
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3908
final_rank: 9

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
 
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, int> pii;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
 
 
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
 
#define MOD 1000000007
 
template<class T1, class T2> inline bool chmax(T1 &a, T2 b) {if (a < b) {a = b; return true;} return false;}
template<class T1, class T2> inline bool chmin(T1 &a, T2 b) {if (a > b) {a = b; return true;} return false;}
const double EPS = 1e-8, PI = acos(-1);
const double pi = 3.141592653589793238462643383279;
//ここから編集    
typedef string::const_iterator State;
ll GCD(ll a, ll b){
  return (b==0)?a:GCD(b, a%b);
}
ll LCM(ll a, ll b){
  return a/GCD(a, b) * b;
}
template< int mod >
struct ModInt {
  int x;
 
  ModInt() : x(0) {}
 
  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
 
  ModInt &operator+=(const ModInt &p) {
    if((x += p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator-=(const ModInt &p) {
    if((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator*=(const ModInt &p) {
    x = (int) (1LL * x * p.x % mod);
    return *this;
  }
 
  ModInt &operator/=(const ModInt &p) {
    *this *= p.inverse();
    return *this;
  }
 
  ModInt operator-() const { return ModInt(-x); }
 
  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
 
  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
 
  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
 
  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
 
  bool operator==(const ModInt &p) const { return x == p.x; }
 
  bool operator!=(const ModInt &p) const { return x != p.x; }
 
  ModInt inverse() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while(b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }
 
  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while(n > 0) {
      if(n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
 
  friend ostream &operator<<(ostream &os, const ModInt &p) {
    return os << p.x;
  }
 
  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt< mod >(t);
    return (is);
  }
 
  static int get_mod() { return mod; }
};
 
using modint = ModInt< 998244353 >;
template< typename T >
struct Combination {
  vector< T > _fact, _rfact, _inv;
 
  Combination(int sz) : _fact(sz + 1), _rfact(sz + 1), _inv(sz + 1) {
    _fact[0] = _rfact[sz] = _inv[0] = 1;
    for(int i = 1; i <= sz; i++) _fact[i] = _fact[i - 1] * i;
    _rfact[sz] /= _fact[sz];
    for(int i = sz - 1; i >= 0; i--) _rfact[i] = _rfact[i + 1] * (i + 1);
    for(int i = 1; i <= sz; i++) _inv[i] = _rfact[i] * _fact[i - 1];
  }
 
  inline T fact(int k) const { return _fact[k]; }
 
  inline T rfact(int k) const { return _rfact[k]; }
 
  inline T inv(int k) const { return _inv[k]; }
 
  T P(int n, int r) const {
    if(r < 0 || n < r) return 0;
    return fact(n) * rfact(n - r);
  }
 
  T C(int p, int q) const {
    if(q < 0 || p < q) return 0;
    return fact(p) * rfact(q) * rfact(p - q);
  }
 
  T H(int n, int r) const {
    if(n < 0 || r < 0) return (0);
    return r == 0 ? 1 : C(n + r - 1, r);
  }
};
 
ll modpow(ll x, ll n, ll mod) {
  ll res = 1;
  x %= mod;
  if(x == 0) return 0;
  while(n) {
    if(n&1) res = (res * x) % mod;
    x = (x * x) % mod;
    n >>= 1;
  }
  return res;
} 
inline long long mod(long long a, long long m) {
    return (a % m + m) % m;
}
template<typename T> 
struct BIT{
  int N;
  std::vector<T> node;
  BIT(){}
  BIT(int n){
    N = n;
    node.resize(N+10);
  }
  void build(int n) {
    N = n;
    node.resize(N+10);
  }
  /* a: 1-indexed */
  void add(int a, T x){
    for(int i=a; i<(int)node.size(); i += i & -i) node[i] += x;
  }

  /* [1, a] */
  T sum(int a){
    T res = 0;
    for(int x=a; x>0; x -= x & -x) res += node[x];
    return res;
  }

  /* [l, r] */
  T rangesum(int l, int r){
    return sum(r) - sum(l-1);
  }

  /* 
    a1+a2+...+aw >= valとなるような最小のwを返す
    @verify https://codeforces.com/contest/992/problem/E
  */
  int lower_bound(T val) {
    if(val < 0) return 0;

    int res = 0;
    int n = 1; 
    while (n < N) n *= 2;

    T tv=0;
    for (int k = n; k > 0; k /= 2) {
      if(res + k < N && node[res + k] < val){
        val -= node[res+k];
        res += k;
      }
    }
    return res+1; 
  }
};
struct UnionFind{
  std::vector<int> par;
  std::vector<int> siz;

  UnionFind(int sz_): par(sz_), siz(sz_) {
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  void init(int sz_){
    par.resize(sz_);
    siz.resize(sz_);
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  int root(int x){
    if(x == par[x]) return x;
    return par[x] = root(par[x]);
  }

  bool merge(int x, int y){
    x = root(x), y = root(y);
    if(x == y) return false;
    if(siz[x] < siz[y]) std::swap(x, y);
    siz[x] += siz[y];
    par[y] = x;
    return true;
  }

  bool issame(int x, int y){
    return root(x) == root(y);
  }

  int size(int x){
    return siz[root(x)];
  }
};
struct RollingHash{

    using ull = unsigned long long;
    const ull mod = (1ULL << 61) - 1;
    const ull MASK30 = (1ULL << 30) - 1;
    const ull MASK31 = (1ULL << 31) - 1;

    const ull MASK61 = mod;

    ull base;
    int n;
    vector<ull> hash, pow;

    RollingHash(const string &s)
    {
        random_device rnd;
        mt19937_64 mt(rnd());
        base = 1001;
        
        n = (int)s.size();
        hash.assign(n+1, 0);
        pow.assign(n+1, 1);
        
        for(int i=0; i<n; i++){
            hash[i+1] = calc_mod(mul(hash[i], base) + s[i]);
            pow[i+1] = calc_mod(mul(pow[i], base));
        }
    }

    ull calc_mod(ull x){
        ull xu = x >> 61;
        ull xd = x & MASK61;
        ull res = xu + xd;
        if(res >= mod) res -= mod;
        return res;
    }

    ull mul(ull a, ull b){
        ull au = a >> 31;
        ull ad = a & MASK31;
        ull bu = b >> 31;
        ull bd = b & MASK31;
        ull mid = ad * bu + au * bd;
        ull midu = mid >> 30;
        ull midd = mid & MASK30;
        return calc_mod(au * bu * 2 + midu + (midd << 31) + ad * bd);
    }

    //[l,r)のハッシュ値
    inline ull get(int l, int r){
        ull res = calc_mod(hash[r] + mod*3-mul(hash[l], pow[r-l]));
        return res;
    }
    //string tのハッシュ値
    inline ull get(string t){
        ull res = 0;
        for(int i=0; i<t.size(); i++){
            res = calc_mod(mul(res, base)+t[i]);
        }
        return res;
    }
    //string s中のtの数をカウント
    inline int count(string t) {
        if(t.size() > n) return 0;
        auto hs = get(t);
        int res = 0;
        for(int i=0; i<n-t.size()+1; i++){
            if(get(i, i+t.size()) == hs) res++; 
        }
        return res;
    }

    /* 
        concat 
        @verify https://codeforces.com/problemset/problem/514/C
    */
    inline ull concat(ull h1, ull h2, int h2len){
      return calc_mod(h2 + mul(h1, pow[h2len]));
    }

    // LCPを求める S[a:] T[b:]
    inline int LCP(int a, int b){
        int len = min((int)hash.size()-a, (int)hash.size()-b);
        
        int lb = -1, ub = len;
        while(ub-lb>1){
            int mid = (lb+ub)/2;

            if(get(a, a+mid) == get(b, b+mid)) lb = mid;
            else ub = mid;
        }
        return lb;
    }
};
template< typename flow_t, typename cost_t >
struct PrimalDual {
  const cost_t INF;

  struct edge {
    int to;
    flow_t cap;
    cost_t cost;
    int rev;
    bool isrev;
  };
  vector< vector< edge > > graph;
  vector< cost_t > potential, min_cost;
  vector< int > prevv, preve;

  PrimalDual(int V) : graph(V), INF(numeric_limits< cost_t >::max()) {}

  void add_edge(int from, int to, flow_t cap, cost_t cost) {
    graph[from].emplace_back((edge) {to, cap, cost, (int) graph[to].size(), false});
    graph[to].emplace_back((edge) {from, 0, -cost, (int) graph[from].size() - 1, true});
  }

  cost_t min_cost_flow(int s, int t, flow_t f) {
    int V = (int) graph.size();
    cost_t ret = 0;
    using Pi = pair< cost_t, int >;
    priority_queue< Pi, vector< Pi >, greater< Pi > > que;
    potential.assign(V, 0);
    preve.assign(V, -1);
    prevv.assign(V, -1);

    while(f > 0) {
      min_cost.assign(V, INF);
      que.emplace(0, s);
      min_cost[s] = 0;
      while(!que.empty()) {
        Pi p = que.top();
        que.pop();
        if(min_cost[p.second] < p.first) continue;
        for(int i = 0; i < graph[p.second].size(); i++) {
          edge &e = graph[p.second][i];
          cost_t nextCost = min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
          if(e.cap > 0 && min_cost[e.to] > nextCost) {
            min_cost[e.to] = nextCost;
            prevv[e.to] = p.second, preve[e.to] = i;
            que.emplace(min_cost[e.to], e.to);
          }
        }
      }
      if(min_cost[t] == INF) return -1;
      for(int v = 0; v < V; v++) potential[v] += min_cost[v];
      flow_t addflow = f;
      for(int v = t; v != s; v = prevv[v]) {
        addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
      }
      f -= addflow;
      ret += addflow * potential[t];
      for(int v = t; v != s; v = prevv[v]) {
        edge &e = graph[prevv[v]][preve[v]];
        e.cap -= addflow;
        graph[v][e.rev].cap += addflow;
      }
    }
    return ret;
  }

  void output() {
    for(int i = 0; i < graph.size(); i++) {
      for(auto &e : graph[i]) {
        if(e.isrev) continue;
        auto &rev_e = graph[e.to][e.rev];
        cout << i << "->" << e.to << " (flow: " << rev_e.cap << "/" << rev_e.cap + e.cap << ")" << endl;
      }
    }
  }
};
int main() {  
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(12);
  
  int n; cin >> n;
  vector<int> p(n);
  int s = 2*n, t = s+1;
  PrimalDual<int, int> g(2*n+2);
  REP(i,n) {
    g.add_edge(s, i, 1, 0);
    g.add_edge(i+n, t, 1, 0);
  }
  REP(i,n) {
    cin >> p[i];
    p[i]--;
    REP(j,n) {
      if(p[i] == j) continue;
      g.add_edge(i, j+n, 1, (p[i]+1)*abs(i-j));
    }
  }
  cout << g.min_cost_flow(s, t, n) << endl;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3840
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define elif else if
#define sp(x) fixed << setprecision(x)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const int inf = (1<<30)-1;
const ll INF = (1LL<<60)-1;
const ld EPS = 1e-10;
template<typename T> bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;};
template<typename T> bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;};

template<typename T>
struct Min_Cost_Flow{
    struct edge{
        int to; T cap, cost; int rev;
        edge(int to, T cap, T cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {}
    };

    vector<vector<edge>> es;
    vector<T> d, h;
    vector<int> pre_v, pre_e;
    const int INF_T;

    Min_Cost_Flow(int n) : INF_T(numeric_limits<T>::max()){
        es.resize(n), d.resize(n), h.resize(n), pre_v.resize(n), pre_e.resize(n);
    }

    void add_edge(int from, int to, T cap, T cost){
        es[from].eb(to, cap, cost, sz(es[to]));
        es[to].eb(from, 0, -cost, sz(es[from])-1);
    }

    void dijkstra(int s){
        fill(all(d), INF_T);
        using P = pair<T, int>;
        priority_queue<P, vector<P>, greater<P> > que;
        que.emplace(d[s] = 0, s);
        while(!que.empty()){
            T p; int i;
            tie(p, i) = que.top(); que.pop();
            if(p > d[i]) continue;
            rep(j, sz(es[i])){
                edge &e = es[i][j];
                if(e.cap > 0 && chmin(d[e.to], d[i]+e.cost+h[i]-h[e.to])){
                    pre_v[e.to] = i, pre_e[e.to] = j;
                    que.emplace(d[e.to], e.to);
                }
            }
        }
    }

    T min_cost_flow(int s, int t, T flow){
        T ret = 0;
        fill(all(h), 0);
        while(flow > 0){
            dijkstra(s);
            if(d[t] == INF_T) return -1;
            rep(i, sz(es)){
                if(h[i] == INF_T || d[i] == INF_T) h[i] = INF_T;
                else h[i] += d[i];
            }
            T f = flow;
            for(int now = t; now != s; now = pre_v[now]){
                chmin(f, es[pre_v[now]][pre_e[now]].cap);
            }
            ret += f*h[t], flow -= f;
            for(int now = t; now != s; now = pre_v[now]){
                edge &e = es[pre_v[now]][pre_e[now]];
                e.cap -= f, es[now][e.rev].cap += f;
            }
        }
        return ret;
    }
};

int main(){
    int N;
    cin >> N;
    int p[N];
    rep(i, N) cin >> p[i];
    Min_Cost_Flow<int> G(2*N+2);
    int s = 2*N, t = 2*N+1;
    rep(i, N){
        G.add_edge(s, i, 1, 0), G.add_edge(N+i, t, 1, 0);
        rep(j, N){
            if(j == p[i]-1) continue;
            G.add_edge(i, N+j, 1, p[i]*abs(j-i));
        }
    }
    cout << G.min_cost_flow(s, t, N) << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 3472
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }


#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P)
{ return s << '<' << P.first << ", " << P.second << '>'; }
template<class T> ostream& operator << (ostream &s, vector<T> P)
{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << " "; } s << P[i]; } return s; }
template<class T> ostream& operator << (ostream &s, vector<vector<T> > P)
{ for (int i = 0; i < P.size(); ++i) { s << endl << P[i]; } return s << endl; }
template<class T> ostream& operator << (ostream &s, set<T> P)
{ for(auto it : P) { s << "<" << it << "> "; } return s << endl; }
template<class T1, class T2> ostream& operator << (ostream &s, map<T1,T2> P)
{ for(auto it : P) { s << "<" << it.first << "->" << it.second << "> "; } return s << endl; }


// edge class (for network-flow)
template<class FLOWTYPE, class COSTTYPE> struct Edge {
    int rev, from, to, id;
    FLOWTYPE cap, icap;
    COSTTYPE cost;
    Edge(int r, int f, int t, FLOWTYPE ca, COSTTYPE co, int id = -1) :
        rev(r), from(f), to(t), cap(ca), icap(ca), cost(co), id(id) {}
    friend ostream& operator << (ostream& s, const Edge& E) {
        if (E.cap > 0)
            return s << E.from << "->" << E.to <<
                '(' << E.cap << ',' << E.cost << ')';
        else return s;
    }
};

// graph class (for network-flow)
template<class FLOWTYPE, class COSTTYPE> struct Graph {
    vector<vector<Edge<FLOWTYPE, COSTTYPE> > > list;
    
    Graph(int n = 0) : list(n) { }
    void init(int n = 0) { list.clear(); list.resize(n); }
    void reset() { for (int i = 0; i < (int)list.size(); ++i) for (int j = 0; j < list[i].size(); ++j) list[i][j].cap = list[i][j].icap; }
    inline vector<Edge<FLOWTYPE, COSTTYPE> >& operator [] (int i) { return list[i]; }
    inline const size_t size() const { return list.size(); }
    
    inline Edge<FLOWTYPE, COSTTYPE> &redge(const Edge<FLOWTYPE, COSTTYPE> &e) {
        if (e.from != e.to) return list[e.to][e.rev];
        else return list[e.to][e.rev + 1];
    }
    
    void addedge(int from, int to, FLOWTYPE cap, COSTTYPE cost, int id = -1) {
        list[from].push_back(Edge<FLOWTYPE, COSTTYPE>((int)list[to].size(), from, to, cap, cost, id));
        list[to].push_back(Edge<FLOWTYPE, COSTTYPE>((int)list[from].size() - 1, to, from, 0, -cost));
    }
    
    void add_undirected_edge(int from, int to, FLOWTYPE cap, COSTTYPE cost, int id = -1) {
        list[from].push_back(Edge<FLOWTYPE, COSTTYPE>((int)list[to].size(), from, to, cap, cost, id));
        list[to].push_back(Edge<FLOWTYPE, COSTTYPE>((int)list[from].size() - 1, to, from, cap, cost, id));
    }

    friend ostream& operator << (ostream& s, const Graph& G) {
        s << endl;
        for (int i = 0; i < G.size(); ++i) {
            s << i << ":";
            for (auto e : G.list[i]) s << " " << e;
            s << endl;
        }
        return s;
    }   
};

// min-cost flow (by primal-dual)
template<class FLOWTYPE, class COSTTYPE> COSTTYPE MinCostFlow(Graph<FLOWTYPE, COSTTYPE> &G, int s, int t, FLOWTYPE f) {
    int n = (int)G.size();
    vector<COSTTYPE> pot(n, 0), dist(n, -1);
    vector<int> prevv(n), preve(n);
    COSTTYPE res = 0;
    while (f > 0) {
        priority_queue<pair<COSTTYPE,int>, vector<pair<COSTTYPE,int> >, greater<pair<COSTTYPE,int> > > que;
        dist.assign(n, -1);
        dist[s] = 0;
        que.push(make_pair(0,s));
        while(!que.empty()) {
            pair<COSTTYPE,int> p = que.top();
            que.pop();
            int v = p.second;
            if (dist[v] < p.first) continue;
            for (int i = 0; i < G[v].size(); ++i) {
                auto e = G[v][i];
                if (e.cap > 0 && (dist[e.to] < 0 || dist[e.to] > dist[v] + e.cost + pot[v] - pot[e.to])) {
                    dist[e.to] = dist[v] + e.cost + pot[v] - pot[e.to];
                    prevv[e.to] = v;
                    preve[e.to] = i;
                    que.push(make_pair(dist[e.to], e.to));
                }
            }
        }
        if (dist[t] < 0) return -1;
        for (int v = 0; v < n; ++v) pot[v] += dist[v];
        FLOWTYPE d = f;
        for (int v = t; v != s; v = prevv[v]) {
            d = min(d, G[prevv[v]][preve[v]].cap);
        }
        f -= d;
        res += pot[t] * d;
        for (int v = t; v != s; v = prevv[v]) {
            Edge<FLOWTYPE,COSTTYPE> &e = G[prevv[v]][preve[v]];
            Edge<FLOWTYPE,COSTTYPE> &re = G.redge(e);
            e.cap -= d;
            re.cap += d;
        }
    }
    return res;
}



int main() {
    int N; cin >> N;
    vector<int> p(N);
    for (int i = 0; i < N; ++i) cin >> p[i], --p[i];

    Graph<int, long long> G(N*2+2);
    int s = N*2, t = N*2+1;
    for (int i = 0; i < N; ++i) {
        G.addedge(s, i, 1, 0);
        G.addedge(i+N, t, 1, 0);
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            if (p[i] == j) continue;
            G.addedge(i, j+N, 1, (p[i]+1)*abs(i-j));
        }
    }
    auto res = MinCostFlow(G, s, t, N);
    cout << res << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 3832
final_rank: 6

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#define _USE_MATH_DEFINES
#include <cmath>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()

const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
// const int MOD = 998244353;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
// const int dy[] = {1, 1, 0, -1, -1, -1, 0, 1},
//           dx[] = {0, -1, -1, -1, 0, 1, 1, 1};

struct IOSetup {
  IOSetup() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    cerr << fixed << setprecision(10);
  }
} iosetup;
/*-------------------------------------------------*/
template <typename T, typename U>
struct PrimalDual {
  using Pui = pair<U, int>;

  struct Edge {
    int dst, rev;
    T cap;
    U cost;
    Edge(int dst, T cap, U cost, int rev) : dst(dst), cap(cap), cost(cost), rev(rev) {}
  };

  vector<vector<Edge> > graph;

  PrimalDual(int n, T TINF, U UINF) : n(n), TINF(TINF), UINF(UINF), graph(n), prev_v(n, -1), prev_e(n, -1), potential(n, 0), dist(n) {}

  void add_edge(int src, int dst, T cap, U cost) {
    has_negative_edge |= cost < 0;
    graph[src].emplace_back(dst, cap, cost, graph[dst].size());
    graph[dst].emplace_back(src, 0, -cost, graph[src].size() - 1);
  }

  U minimum_cost_flow(int s, int t, T flow) {
    U res = 0;
    if (has_negative_edge) {
      bellman_ford(s);
      if (dist[t] == UINF) return UINF;
      res += calc(s, t, flow);
    }
    while (flow > 0) {
      dijkstra(s);
      if (dist[t] == UINF) return UINF;
      res += calc(s, t, flow);
    }
    return res;
  }

  U minimum_cost_flow(int s, int t) {
    U res = 0;
    bellman_ford(s);
    if (potential[t] >= 0 || dist[t] == UINF) return res;
    T tmp = TINF;
    res += calc(s, t, tmp);
    while (true) {
      dijkstra(s);
      if (potential[t] >= 0 || dist[t] == UINF) return res;
      res += calc(s, t, tmp);
    }
  }

  pair<T, U> min_cost_max_flow(int s, int t, T flow) {
    T mx = flow;
    U cost = 0;
    if (has_negative_edge) {
      bellman_ford(s);
      if (dist[t] == UINF) return {mx - flow, cost};
      cost += calc(s, t, flow);
    }
    while (flow > 0) {
      dijkstra(s);
      if (dist[t] == UINF) return {mx - flow, cost};
      cost += calc(s, t, flow);
    }
    return {mx - flow, cost};
  }

private:
  int n;
  T TINF;
  U UINF;
  bool has_negative_edge = false;
  vector<int> prev_v, prev_e;
  vector<U> potential, dist;
  priority_queue<Pui, vector<Pui>, greater<Pui> > que;

  void bellman_ford(int s) {
    fill(ALL(dist), UINF);
    dist[s] = 0;
    bool is_updated = true;
    REP(step, n) {
      is_updated = false;
      REP(i, n) if (dist[i] != UINF) {
        REP(j, graph[i].size()) {
          Edge e = graph[i][j];
          if (e.cap > 0 && dist[e.dst] > dist[i] + e.cost) {
            dist[e.dst] = dist[i] + e.cost;
            prev_v[e.dst] = i;
            prev_e[e.dst] = j;
            is_updated = true;
          }
        }
      }
      if (!is_updated) break;
    }
    assert(!is_updated);
    REP(i, n) {
      if (dist[i] != UINF) potential[i] += dist[i];
    }
  }

  void dijkstra(int s) {
    fill(ALL(dist), UINF);
    dist[s] = 0;
    que.emplace(0, s);
    while (!que.empty()) {
      Pui pr = que.top(); que.pop();
      int ver = pr.second;
      if (dist[ver] < pr.first) continue;
      REP(i, graph[ver].size()) {
        Edge e = graph[ver][i];
        U nx = dist[ver] + e.cost + potential[ver] - potential[e.dst];
        if (e.cap > 0 && dist[e.dst] > nx) {
          dist[e.dst] = nx;
          prev_v[e.dst] = ver;
          prev_e[e.dst] = i;
          que.emplace(dist[e.dst], e.dst);
        }
      }
    }
    REP(i, n) {
      if (dist[i] != UINF) potential[i] += dist[i];
    }
  }

  U calc(int s, int t, T &flow) {
    T f = flow;
    for (int v = t; v != s; v = prev_v[v]) f = min(f, graph[prev_v[v]][prev_e[v]].cap);
    flow -= f;
    for (int v = t; v != s; v = prev_v[v]) {
      Edge &e = graph[prev_v[v]][prev_e[v]];
      e.cap -= f;
      graph[v][e.rev].cap += f;
    }
    return potential[t] * f;
  }
};

template <typename T>
struct WeightedBipartiteMatching {
  WeightedBipartiteMatching(int left, int right, T TINF) : left(left), right(right), pd(left + right + 2, INF, TINF) {}

  void add_edge(int src, int dst, T cost) { pd.add_edge(src, left + dst, 1, -cost); }

  T solve() {
    REP(i, left) pd.add_edge(left + right, i, 1, 0);
    REP(i, right) pd.add_edge(left + i, left + right + 1, 1, 0);
    return -pd.min_cost_max_flow(left + right, left + right + 1, left).second;
  }

  vector<int> matching() {
    vector<int> res(left, -1);
    REP(i, left) {
      for (auto e : pd.graph[i]) {
        if (e.cap == 0 && left <= e.dst && e.dst < left + right) {
          res[i] = e.dst - left;
          break;
        }
      }
    }
    return res;
  }

private:
  int left, right;
  PrimalDual<int, T> pd;
};

int main() {
  int n; cin >> n;
  vector<int> p(n);
  REP(i, n) {
    cin >> p[i]; --p[i];
  }
  WeightedBipartiteMatching<int> wbm(n, n, INF);
  REP(i, n) {
    REP(j, n) {
      if (p[i] == j) continue;
      wbm.add_edge(i, j, -(p[i] + 1) * abs(i - j));
    }
  }
  cout << -wbm.solve() << '\n';
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3448
final_rank: 1

code_snippet: #include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
#include <fstream>
#define popcount __builtin_popcount
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
const int INF=1e9+7;
struct edge{
    int to, cap, cost, rev;
};

int V;
vector<edge> g[202];
int h[202];
int dist[202];
int prevv[202], preve[202];

void add_edge(int from, int to, int cap, int cost){
    edge e;
    e.to=to, e.cap=cap, e.cost=cost, e.rev=g[to].size();
    g[from].push_back(e);
    e.to=from, e.cap=0, e.cost=-cost, e.rev=g[from].size()-1;
    g[to].push_back(e);
}
  
int min_cost_flow(int s, int t, int f){
    int res=0;
    fill(h, h+V, 0);
    while(f>0){
        priority_queue<P, vector<P>, greater<P>> que;
        fill(dist, dist+V, INF);
        dist[s]=0;
        que.push(P(0, s));
        while(!que.empty()){
            P p=que.top(); que.pop();
            int v=p.second;
            if(dist[v]<p.first) continue;
            for(int i=0; i<g[v].size(); i++){
                edge &e=g[v][i];
                if(e.cap>0 && dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
                    dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
                    prevv[e.to]=v;
                    preve[e.to]=i;
                    que.push(P(dist[e.to], e.to));
                }
            }
        }
        for(int v=0; v<V; v++) h[v]+=dist[v];
        if(dist[t]==INF) return -1;
        int d=f;
        for(int v=t; v!=s; v=prevv[v]){
            d=min(d, g[prevv[v]][preve[v]].cap);
        }
        f-=d;
        res+=d*h[t];
        for(int v=t; v!=s; v=prevv[v]){
            edge &e=g[prevv[v]][preve[v]];
            e.cap-=d;
            g[v][e.rev].cap+=d;
        }
    }
    return res;
}

int main()
{
    int n; cin>>n;
    int ind[101];
    for(int i=0; i<n; i++){
        int p; cin>>p; p--;
        ind[p]=i;
    }
    V=2*n+2;
    int s=V-1, t=V-2;
    for(int i=0; i<n; i++){
        add_edge(s, i, 1, 0);
        add_edge(i+n, t, 1, 0);
        for(int j=0; j<n; j++){
            if(i==j) continue;
            add_edge(i, j+n, 1, abs(ind[i]-j)*(i+1));
        }
    }
    cout<<min_cost_flow(s, t, n)<<endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3484
final_rank: 4

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;



#define NUM 210


struct Edge{
	Edge(int arg_to,int arg_capacity,int arg_cost,int arg_rev_index){
		to = arg_to;
		capacity = arg_capacity;
		cost = arg_cost;
		rev_index = arg_rev_index;
	}

	int to,capacity,cost,rev_index;
};

int V;
vector<Edge> G[NUM];
int dist[NUM];
int pre_node[NUM],pre_edge[NUM];


void add_edge(int from,int to,int capacity,int cost){
	G[from].push_back(Edge(to,capacity,cost,G[to].size()));
	G[to].push_back(Edge(from,0,-cost,G[from].size()-1));
}

int min_cost_flow(int source,int sink,int flow){
	int ret = 0;
	while(flow > 0){
		for(int i = 0; i < V; i++)dist[i] = BIG_NUM;
		dist[source] = 0;
		bool update = true;
		while(update){
			update = false;
			for(int node_id = 0; node_id < V; node_id++){
				if(dist[node_id] == BIG_NUM)continue;
				for(int i = 0; i < G[node_id].size(); i++){
					Edge &e = G[node_id][i];
					if(e.capacity > 0 && dist[e.to] > dist[node_id]+e.cost){
						dist[e.to] = dist[node_id]+e.cost;
						pre_node[e.to] = node_id;
						pre_edge[e.to] = i;
						update = true;
					}
				}
			}
		}

		if(dist[sink] == BIG_NUM){
			return -1;
		}

		int tmp_flow = flow;
		for(int node_id = sink; node_id != source; node_id = pre_node[node_id]){
			tmp_flow = min(tmp_flow,G[pre_node[node_id]][pre_edge[node_id]].capacity);
		}
		flow -= tmp_flow;
		ret += tmp_flow*dist[sink];
		for(int node_id = sink; node_id != source; node_id = pre_node[node_id]){
			Edge &e = G[pre_node[node_id]][pre_edge[node_id]];
			e.capacity -= tmp_flow;
			G[node_id][e.rev_index].capacity += tmp_flow;
		}
	}
	return ret;
}

int main(){

	int N;
	scanf("%d",&N);

	int source = 0,sink = 1,index = 2;
	int value_table[N],first_index_table[N],final_index_table[N];


	for(int i = 0; i < N; i++){
		first_index_table[i] = index++;
		add_edge(source,first_index_table[i],1,0);
	}

	for(int i = 0; i < N; i++){
		final_index_table[i] = index++;
		add_edge(final_index_table[i],sink,1,0);
	}

	V = index;

	for(int i = 0; i < N; i++){
		scanf("%d",&value_table[i]);
		for(int k = 0; k < N; k++){
			if(k == value_table[i]-1)continue;

			add_edge(first_index_table[i],final_index_table[k],1,value_table[i]*(abs(i-k)));
		}
	}

	printf("%d\n",min_cost_flow(source,sink,N));

	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3448
final_rank: 10

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define int long long
#define all(v) (v).begin(), (v).end()
#define resz(v, ...) (v).clear(), (v).resize(__VA_ARGS__)
#define reps(i, m, n) for(int i = (int)(m); i < (int)(n); i++)
#define rep(i, n) reps(i, 0, n)

template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;}

using Pi = pair<int, int>;
using Ti = tuple<int, int, int>;
using vint = vector<int>;

const int inf = 1LL << 55;
const int mod = 1e9 + 7;

struct edge {
  int to, cap, cost, rev;
  edge(){}
  edge(int to, int cap, int cost, int rev)
    :to(to), cap(cap), cost(cost), rev(rev){}
};

using Graph = vector<vector<edge>>;

struct PrimalDual {
  Graph graph;
  vint mincost, h, prevv, preve;
  PrimalDual(int V):graph(V), mincost(V), h(V), prevv(V), preve(V){}
  void add_edge(int from, int to, int cap, int cost) {
    graph[from].emplace_back(to, cap, cost, graph[to].size());
    graph[to].emplace_back(from, 0, -cost, graph[from].size()-1);
  }
  int min_cost_flow(int s, int t, int f) {
    fill(all(h), 0);
    fill(all(prevv), -1);
    fill(all(preve), -1);
    int res = 0;
    while(f > 0) {
      fill(all(mincost), inf);
      priority_queue<Pi, vector<Pi>, greater<Pi>> que;
      que.emplace(0, s);
      mincost[s] = 0;
      while(!que.empty()) {
	Pi p = que.top(); que.pop();
	int v = p.second;
	if(mincost[v] < p.first) continue;
	rep(i, graph[v].size()) {
	  edge& e = graph[v][i];
	  int cost = mincost[v] + e.cost + h[v] - h[e.to];
	  if(e.cap > 0 && cost < mincost[e.to]) {
	    mincost[e.to] = cost;
	    que.emplace(cost, e.to);
	    prevv[e.to] = v;
	    preve[e.to] = i;
	  }
	}
      }
      if(mincost[t] == inf) return -1;
      rep(v, graph.size()) h[v] += mincost[v];
      int d = f;
      for(int v = t; v != s; v = prevv[v])
	chmin(d, graph[prevv[v]][preve[v]].cap);
      f -= d;
      res += d*h[t];
      for(int v = t; v != s; v = prevv[v]) {
	edge& e = graph[prevv[v]][preve[v]];
	e.cap -= d;
	graph[e.to][e.rev].cap += d;
      }
    }
    return res;
  }
};

signed main()
{
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  int n;
  cin >> n;
  vint p(n);
  rep(i, n) cin >> p[i];
  int s = n*2, t = s+1, V = t+1;
  PrimalDual graph(V);
  rep(i, n) {
    graph.add_edge(s, i, 1, 0);
    graph.add_edge(n+i, t, 1, 0);
  }
  rep(i, n) rep(j, n) {
    if(p[i]-1 == j) continue;
    int cost = p[i]*abs(i-j);
    graph.add_edge(i, n+j, 1, cost);
  }
  cout << graph.min_cost_flow(s, t, n) << endl;

  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3956
final_rank: 11

code_snippet: #include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#include<typeinfo>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
//#define int ll
typedef int Def;
typedef pair<Def,Def> pii;
typedef vector<Def> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<Def,pii> pip;
typedef vector<pip>vip;
//#define mt make_tuple
//typedef tuple<pii,int,int> tp;
//typedef vector<tp> vt;
template<typename A,typename B>bool cmin(A &a,const B &b){return a>b?(a=b,true):false;}
template<typename A,typename B>bool cmax(A &a,const B &b){return a<b?(a=b,true):false;}
//template<class C>constexpr int size(const C &c){return (int)c.size();}
//template<class T,size_t N> constexpr int size(const T (&xs)[N])noexcept{return (int)N;}
const double PI=acos(-1);
const double EPS=1e-7;
Def inf = sizeof(Def) == sizeof(long long) ? 2e18 : 1e9;
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
struct edge{
	int to,cap,cost,rev;
};
typedef vector<edge> ve;
typedef vector<ve> vve;
class MCF{	//Minimum Cost Flow
	public:
	int n;
	vve G;
	vi h,dist,prev,pree;
	MCF(int size){
		n=size;
		G=vve(n);
		h=dist=prev=pree=vi(n);
	}
	void add_edge(int s,int t,int ca,int co){
		edge e={t,ca,co,G[t].size()};
		G[s].pb(e);
		edge ee={s,0,-co,G[s].size()-1};
		G[t].pb(ee);
	}
	int mcf(int s,int t,int f){
		int out=0;
		h=vi(n);
		while(f>0){			
			priority_queue<pii,vector<pii> >q;
			dist=vi(n,inf);
			dist[s]=0;
			q.push(pii(0,s));
			while(!q.empty()){
				pii p=q.top();q.pop();
				int v=p.second;
				if(dist[v]<-p.first)continue;
				rep(i,G[v].size()){
					edge &e=G[v][i];
					if(e.cap>0&&dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
						dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
						prev[e.to]=v;
						pree[e.to]=i;
						q.push(pii(-dist[e.to],e.to));
					}
				}
			}
			if(dist[t]==inf)return -1;
			rep(i,n)h[i]+=dist[i];
			int d=f;
			for(int v=t;v!=s;v=prev[v])d=min(d,G[prev[v]][pree[v]].cap);
			f-=d;
			out+=d*h[t];
			for(int v=t;v!=s;v=prev[v]){
				edge &e=G[prev[v]][pree[v]];
				e.cap-=d;
				G[v][e.rev].cap+=d;
			}
		}
		return out;	
	}
};
signed main(){
	int n;
	cin>>n;
	vi in(n);
	rep(i,n)cin>>in[i];
	MCF mcf(n*2+2);
	int s=n*2,t=s+1;
	rep(i,n)mcf.add_edge(s,i,1,0);
	rep(i,n)mcf.add_edge(n+i,t,1,0);
	vi T(n);
	rep(i,n)T[in[i]-1]=i;
	rep(i,n){
		if(i!=in[i]-1){
			mcf.add_edge(T[i],n+i,1,0);
//			cout<<T[i]<<" "<<n+i<<endl;
		}
		rep(j,n)if(i!=j){
//			cout<<j<<" "<<i<<" "<<abs(T[i]-j)*(1+i)<<endl;
			mcf.add_edge(j,n+i,1,abs(T[i]-j)*(1+i));
		}
	}
	cout<<mcf.mcf(s,t,n)<<endl;
}
accuracy: 1
time_ms: 30
memory_kb: 3536
final_rank: 14

code_snippet: #include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif

//#define int long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; }

struct MinimumCostFlow {
	using Flow = int;
	using Cost = int;
	struct Edge {
		int to, rev;
		Flow cap;
		Cost cost;
		Edge() {}
		Edge(int to, int rev, Flow cap, Cost cost) :to(to), rev(rev), cap(cap), cost(cost) {}
	};
	int n;
	vector<vector<Edge>> g;
	vector<int> dist;
	vector<int> prevv, preve;
	MinimumCostFlow(int n) :n(n), g(n), dist(n), prevv(n), preve(n) {}
	void addArc(int from, int to, Flow cap, Cost cost) {
		g[from].emplace_back(to, (int)g[to].size(), cap, cost);
		g[to].emplace_back(from, (int)g[from].size() - 1, 0, -cost);
	}
	// s??????t????????????f???????°??????¨???
	// ??????????????´?????? -1
	Cost minimumCostFlow(int s, int t, Flow f) {
		Cost total = 0;
		while (f > 0) {
			// Bellman-Ford
			fill(dist.begin(), dist.end(), INF);
			dist[s] = 0;
			bool update = true;
			while (update) {
				update = false;
				for (int v = 0; v < n; v++) {
					if (dist[v] == INF)continue;
					for (int i = 0; i < g[v].size(); i++) {
						Edge &e = g[v][i];
						if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
							dist[e.to] = dist[v] + e.cost;
							prevv[e.to] = v;
							preve[e.to] = i;
							update = true;
						}
					}
				}
			}
			// ????????\???????????????
			if (dist[t] == INF)
				return -1;
			// ?????????????????£??????????????????
			int d = f;
			for (int v = t; v != s; v = prevv[v])
				d = min(d, g[prevv[v]][preve[v]].cap);
			f -= d;
			total += d*dist[t];
			for (int v = t; v != s; v = prevv[v]) {
				Edge &e = g[prevv[v]][preve[v]];
				e.cap -= d;
				g[v][e.rev].cap += d;
			}
		}
		return total;
	}
};

signed main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n; cin >> n;
	vector<int> p(n); rep(i, 0, n) {
		cin >> p[i];
	}
	MinimumCostFlow mcf(n + n + 2);
	int s = n + n, t = s + 1;
	rep(i, 0, n) {
		mcf.addArc(s, i, 1, 0);
		mcf.addArc(n + i, t, 1, 0);
	}
	rep(i, 0, n) {
		rep(j, 0, n) {
			if (j == p[i] - 1)continue;
			mcf.addArc(i, n + j, 1, p[i] * abs(i - j));
		}
	}
	cout << mcf.minimumCostFlow(s, t, n) << endl;
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3496
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

using pi = pair<int,int>;

// (?????????, ??????, ?????????, ??????)
struct edge{ int to,cap,cost,rev; };

int V; // TODO:initialize
const int MAX_V = 222; // TODO:initialize
const int INF = 19191919; // TODO:initialize
vector<edge> G[MAX_V];
int h[MAX_V]; // ??????????????£???
int dist[MAX_V];
int prevv[MAX_V], preve[MAX_V]; // ??´??????????????¨???

void add_edge(int from, int to, int cap, int cost){
    G[from].pb({to,cap,cost,(int)G[to].size()});
    G[to].pb({from,0,-cost,(int)G[from].size()-1});
}

// s??????t????????????f???????°??????¨???(???????????????-1)
int min_cost_flow(int s, int t, int f, bool neg = false){
    int res = 0;
    fill(h,h+V,0);
    while(f>0){
        priority_queue<pi,vector<pi>,greater<pi>> pq;
        fill(dist,dist+V,INF);
        dist[s]=0;
        if(neg)
        {
            // bellman-ford??§h?????´??°
            neg = false;
            bool update;
            do{
                update = false;
                rep(v,V){
                    if(dist[v] == INF) continue;
                    rep(i,G[v].size()){
                        edge &e = G[v][i];
                        if(e.cap>0 && dist[e.to]>dist[v]+e.cost){
                            dist[e.to]=dist[v]+e.cost;
                            prevv[e.to] = v;
                            preve[e.to] = i;
                            update = true;
                        }
                    }
                }
            }while(update);
        }
        else
        {
            // dijkstra??§h?????´??°
            pq.push(pi(0,s));
            while(!pq.empty()){
                pi p = pq.top();
                pq.pop();
                int v = p.se;
                if(p.fi>dist[v]) continue;
                rep(i,G[v].size()){
                    edge &e = G[v][i];
                    if(e.cap>0 && dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
                        dist[e.to] = dist[v]+e.cost+h[v]-h[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        pq.push(pi(dist[e.to],e.to));
                    }
                }
            }
        }

        // ????????\???????????????
        if(dist[t]==INF) return -1;

        rep(v,V) h[v] += dist[v];

        // s-t???????????????????????£??????????????????
        int d=f;
        for(int v=t; v!=s; v=prevv[v]) d = min(d,G[prevv[v]][preve[v]].cap);
        f -= d;
        res += d*h[t];

        for(int v=t; v!=s; v=prevv[v]){
            edge &e = G[prevv[v]][preve[v]];
            e.cap -= d;
            G[v][e.rev].cap += d;
        }
    }
    return res;
}

int main()
{
    int n;
    cin >>n;
    vector<int> p(n);
    rep(i,n)
    {
        cin >>p[i];
        --p[i];
    }

    V = 2*n+2;
    int S = 2*n, T = S+1;

    rep(i,n)
    {
        add_edge(S,i,1,0);
        add_edge(n+i,T,1,0);

        rep(j,n)if(p[i]!=j)
        {
            add_edge(i,n+j,1,(p[i]+1)*abs(i-j));
        }
    }

    printf("%d\n", min_cost_flow(S,T,n));
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3640
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int MAX_V = 100010;
typedef int Capacity;
typedef int Cost;
const int inf = 1 << 28;

struct Edge {
	int dst;
	Capacity cap, cap_orig;
	Cost cost;
	int revEdge; bool isRev;
	Edge(int dst, Capacity cap, Cost cost, int revEdge, bool isRev)
		:dst(dst), cap(cap), cap_orig(cap), cost(cost), revEdge(revEdge), isRev(isRev) {
	}
};


struct PrimalDual {
	int n;
	vector<vector<Edge> > g;
	vector<int> top;
	PrimalDual(int n_) : n(n_), g(vector<vector<Edge> >(n_)) {}
	void add_edge(int src, int dst, Capacity cap, Cost cost) { // ?????????
		g[src].push_back(Edge{ dst, cap, cost, (int)g[dst].size(), false });
		g[dst].push_back(Edge{ src, 0, -cost, (int)g[src].size() - 1, true });
	}
	Cost solve(int s, int t, int f) {
		Cost res = 0;
		static Cost h[MAX_V], dist[MAX_V];
		static int prevv[MAX_V], preve[MAX_V];

		fill(h, h + n, 0);
		if(top.size()) {
			assert(top.size() == n);
			for(int i = 0; i < n; i++) {
				int v = top[i];
				for(int i = 0; i < g[v].size(); i++) {
					Edge& e = g[v][i];
					if(e.cap == 0) continue;
					int u = e.dst;
					h[u] = min(h[u], h[v] + e.cost);
				}
			}
		}

		while(f > 0) {
			typedef pair<Cost, int> pcv;
			priority_queue<pcv, vector<pcv>, greater<pcv> > q;
			for(int i = 0; i < n; i++) {
				dist[i] = inf;
			}
			dist[s] = 0;
			q.push(pcv(0, s));
			while(q.size()) {
				pcv p = q.top(); q.pop();
				int v = p.second;
				if(dist[v] < p.first) continue;
				for(int i = 0; i < g[v].size(); i++) {
					Edge &e = g[v][i];
					if(e.cap > 0 && dist[e.dst] > dist[v] + e.cost + h[v] - h[e.dst]) {
						dist[e.dst] = dist[v] + e.cost + h[v] - h[e.dst];
						prevv[e.dst] = v;
						preve[e.dst] = i;
						q.push(pcv(dist[e.dst], e.dst));
					}
				}
			}
			if(dist[t] == inf) {
				return -1;
			}
			for(int v = 0; v < n; v++) {
				h[v] += dist[v];
			}
			// s-t ????????????????????£??????????????????
			int d = f;
			for(int v = t; v != s; v = prevv[v]) {
				d = min(d, g[prevv[v]][preve[v]].cap);
			}
			f -= d;
			res += d * h[t];
			for(int v = t; v != s; v = prevv[v]) {
				Edge &e = g[prevv[v]][preve[v]];
				e.cap -= d;
				g[v][e.revEdge].cap += d;
			}
		}
		return res;
	}
	// ??????????????????=???????????????-?????¨??????????????¨???
	void view() {
		for(int i = 0; i < g.size(); i++) {
			for(int j = 0; j < g[i].size(); j++) {
				if(!g[i][j].isRev) {
					Edge& e = g[i][j];
					printf("%3d->%3d (flow:%d)\n", i, e.dst, e.cap_orig - e.cap);
				}
			}
		}
	}
};

int p[100];

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int N;
	cin >> N;
	for(int i = 0; i < N; i++) {
		cin >> p[i];
	}

	PrimalDual pd(2 * N + 2);
	int S = 2 * N, T = S + 1;
	for(int i = 0; i < N; i++) {
		for(int j = 0; j < N; j++) {
			if(p[i] == j + 1) continue;
			pd.add_edge(i, j + N, 1, p[i] * abs(i - j));
		}
		pd.add_edge(S, i, 1, 0);
		pd.add_edge(i + N, T, 1, 0);
	}

	cout << pd.solve(S, T, N) << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 3700
final_rank: 13

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if(f!=2){
      swap(arr[l],arr[i]);
      Min(res,cal(l,i)+dfs(1,arr[l],l,i-1)+dfs(1,arr[i],i,r));
      swap(arr[l],arr[i]);
    }
    if(f!=1){
      swap(arr[i],arr[r]);
      Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(2,arr[r],i+1,r));
      swap(arr[i],arr[r]);
    }
  }

  for(int i=l;i<r;i++){
    int a=(f==1)? dfs(f,num,l,i):dfs(0,0,l,i);
    int b=(f==2)? dfs(2,num,i+1,r):dfs(0,0,i+1,r);
    Min(res,a+b);
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 1
time_ms: 260
memory_kb: 15188
final_rank: 19

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if(f!=2&&arr[i]!=l+1){
      swap(arr[l],arr[i]);
      Min(res,cal(l,i)+dfs(0,0,l+1,i-1)+dfs(1,arr[i],i,r));
      swap(arr[l],arr[i]);
    }
    if(f!=1&&arr[i]!=r+1){
      swap(arr[i],arr[r]);
      Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(0,0,i+1,r-1));
      swap(arr[i],arr[r]);
    }
  }

  for(int i=l;i<r;i++){
    int a=(f==1)? dfs(f,num,l,i):dfs(0,0,l,i);
    int b=(f==2)? dfs(2,num,i+1,r):dfs(0,0,i+1,r);
    Min(res,a+b);
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 1
time_ms: 130
memory_kb: 15188
final_rank: 15

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if((f==0||f==1)&&arr[i]!=l+1){
      swap(arr[l],arr[i]);
      Min(res,cal(l,i)+dfs(0,0,l+1,i-1)+dfs(1,arr[i],i,r));
      swap(arr[l],arr[i]);
    }
    if((f==0||f==2)&&arr[i]!=r+1){
      swap(arr[i],arr[r]);
      Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(0,0,i+1,r-1));
      swap(arr[i],arr[r]);
    }
  }

  for(int i=l;i<r;i++){
    int a=(f==1)? dfs(f,num,l,i):dfs(0,0,l,i);
    int b=(f==2)? dfs(2,num,i+1,r):dfs(0,0,i+1,r);
    Min(res,a+b);
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 1
time_ms: 180
memory_kb: 15184
final_rank: 18

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if((f==0||f==1)&&arr[i]!=l+1){
      swap(arr[l],arr[i]);
      Min(res,cal(l,i)+dfs(0,0,l+1,i-1)+dfs(1,arr[i],i,r));
      swap(arr[l],arr[i]);
      }
    /*
    if((f==0||f==2)&&arr[i]!=r+1){
      swap(arr[i],arr[r]);
      Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(0,0,i+1,r-1));
      swap(arr[i],arr[r]);
    }
    */
  }

  for(int i=l;i<r;i++){
    if(f==1)Min(res,dfs(1,num,l,i)+dfs(0,0,i+1,r));
    else if(f==2)Min(res,dfs(0,0,l,i)+dfs(2,num,i+1,r));
    else Min(res,dfs(0,0,l,i)+dfs(0,0,i+1,r));
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 0.8494623655913979
time_ms: 70
memory_kb: 15184
final_rank: 20

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if((f==0||f==1)&&arr[i]!=l+1){
      swap(arr[l],arr[i]);
      Min(res,cal(l,i)+dfs(0,0,l+1,i-1)+dfs(1,arr[i],i,r));
      swap(arr[l],arr[i]);
      }

    if((f==0||f==2)&&arr[i]!=r+1){
      swap(arr[i],arr[r]);
      Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(0,0,i+1,r-1));
      swap(arr[i],arr[r]);
    }
  }

  for(int i=l;i<r;i++){
    if(f==1)Min(res,dfs(1,num,l,i)+dfs(0,0,i+1,r));
    else if(f==2)Min(res,dfs(0,0,l,i)+dfs(2,num,i+1,r));
    else Min(res,dfs(0,0,l,i)+dfs(0,0,i+1,r));
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 1
time_ms: 140
memory_kb: 15192
final_rank: 17

code_snippet: #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n,arr[101];
int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));}
void Min(int &a,int b){a=min(a,b);}

int mem[3][101][101][101];
int dfs(int f,int num,int l,int r){
  if(l>r)return 0;
  if(l==r)return (arr[l]==l+1) ? INF:0;
  if(r-l==1)return (arr[l]==l+1||arr[r]==r+1)? cal(l,r):0;
  if(mem[f][num][l][r]!=-1)return mem[f][num][l][r];

  int res=INF;  
  for(int i=l+1;i<r;i++){
    if(f==0||f==1)
      if(arr[i]!=l+1){
	swap(arr[l],arr[i]);
	Min(res,cal(l,i)+dfs(0,0,l+1,i-1)+dfs(1,arr[i],i,r));
	swap(arr[l],arr[i]);
      }

    if(f==0||f==2)
      if(arr[i]!=r+1){
	swap(arr[i],arr[r]);
	Min(res,cal(i,r)+dfs(2,arr[i],l,i)+dfs(0,0,i+1,r-1));
	swap(arr[i],arr[r]);
      }
  }

  for(int i=l;i<r;i++){
    if(f==1)Min(res,dfs(1,num,l,i)+dfs(0,0,i+1,r));
    else if(f==2)Min(res,dfs(0,0,l,i)+dfs(2,num,i+1,r));
    else Min(res,dfs(0,0,l,i)+dfs(0,0,i+1,r));
  }

  return mem[f][num][l][r]=res;
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++)cin>>arr[i];
  memset(mem,-1,sizeof(mem));
  cout<<dfs(0,0,0,n-1)<<endl;
}
accuracy: 1
time_ms: 140
memory_kb: 15184
final_rank: 16

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define REP(i,a,b) for(int i=a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)
#define all(c) (c).begin(), (c).end()
#define zero(a) memset(a, 0, sizeof a)
#define minus(a) memset(a, -1, sizeof a)
#define watch(a) { cout << #a << " = " << a << endl; }
template<class T1, class T2> inline bool minimize(T1 &a, T2 b) { return b < a && (a = b, 1); }
template<class T1, class T2> inline bool maximize(T1 &a, T2 b) { return a < b && (a = b, 1); }

typedef long long ll;
int const inf = 1<<29;

namespace flow {

struct edge {
  int to, cap, cost, rev;
  edge(int t, int ca, int co, int r) : to(t), cap(ca), cost(co), rev(r) {}
};

struct primal_dual {

  vector<vector<edge>> G;
  vector<int> h;
  vector<int> dist;
  vector<int> prevv, preve;

  primal_dual(int V) : G(V), h(V), dist(V), prevv(V), preve(V) {}

  void add_edge(int from, int to, int cap, int cost) {
    G[from].emplace_back(to, cap, cost, G[to].size());
    G[to].emplace_back(from, 0, -cost, G[from].size()-1);
  }

  int min_cost_flow(int s, int t, int f) {
    int ret = 0;
    fill(h.begin(), h.end(), 0);
    while(f > 0) {
      typedef pair<int, int> P;
      priority_queue<P, vector<P>, greater<P>> pq;
      fill(dist.begin(), dist.end(), inf);
      dist[s] = 0;
      pq.emplace(0, s);
      while(!pq.empty()) {
        P p = pq.top(); pq.pop();
        int v = p.second;
        if(dist[v] < p.first) { continue; }
        for(int i=0; i<G[v].size(); i++) {
          auto& e = G[v][i];
          if(e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
            dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
            prevv[e.to] = v;
            preve[e.to] = i;
            pq.emplace(dist[e.to], e.to);
          }
        }
      }

      if(dist[t] == inf) { return -1; }
      for(int i=0; i<h.size(); i++) h[i] += dist[i];

      int d = f;
      for(int i=t; i!=s; i=prevv[i]) {
        d = min(d, G[prevv[i]][preve[i]].cap);
      }
      f -= d;
      ret += d * h[t];
      for(int i=t; i!=s; i=prevv[i]) {
        auto& e = G[prevv[i]][preve[i]];
        e.cap -= d;
        G[i][e.rev].cap += d;
      }
    }
    return ret;
  }

};

}

int main() {

  int N; cin >> N;

  vector<int> ps(N);
  rep(i, N) cin >> ps[i], ps[i]--;

  flow::primal_dual pd(2 * N + 2);

  int SRC = 2 * N, SINK = 2 * N + 1;

  rep(i, N) {
    pd.add_edge(SRC, i, 1, 0);
    pd.add_edge(N + i, SINK, 1, 0);
  }

  rep(i, N) rep(j, N) {
    if(ps[i] != j) {
      pd.add_edge(i, N + j, 1, (ps[i] + 1) * abs(i - j));
    }
  }

  cout << pd.min_cost_flow(SRC, SINK, N) << endl;

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3436
final_rank: 8

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define MAX_V 514
#define INF 1e9
typedef pair<int, int> pii;

struct Edge {
    int to, cap, cost, rev;
    Edge(int to, int cap, int cost, int rev) :
        to(to), cap(cap), cost(cost), rev(rev) {}
};

int V, h[MAX_V], dist[MAX_V];
int prevv[MAX_V], preve[MAX_V];
vector<Edge> G[MAX_V];

void add_edge(int from, int to, int cap, int cost)
{
    G[from].push_back(Edge(to, cap, cost, G[to].size()));
    G[to].push_back(Edge(from, 0, -cost, G[from].size()-1));
}

int min_cost_flow(int s, int t, int f)
{
    int res = 0;
    fill(h, h+V, 0);
    while (f > 0) {
	priority_queue<pii, vector<pii>, greater<pii>> Q;
	fill(dist, dist+V, INF);
	dist[s] = 0;
	Q.push(pii(0, s));
	while (!Q.empty()) {
	    pii p = Q.top(); Q.pop();
	    int v = p.second;
	    if (dist[v] < p.first) continue;
	    for (int i = 0; i < (int)G[v].size(); i++) {
		Edge &e = G[v][i];
		if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
		    dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
		    prevv[e.to] = v; preve[e.to] = i;
		    Q.push(pii(dist[e.to], e.to));
		}
	    }
	}
	if (dist[t] == INF) return -1;
	for (int v = 0; v < V; v++) {
	    h[v] += dist[v];
	}
	int d = f;
	for (int v = t; v != s; v = prevv[v]) {
	    d = min(d, G[prevv[v]][preve[v]].cap);
	}
	f -= d;
	res += d * h[t];
	for (int v = t; v != s; v = prevv[v]) {
	    Edge &e = G[prevv[v]][preve[v]];
	    e.cap -= d;
	    G[v][e.rev].cap += d;
	}
    }
    return res;
}

int main()
{
    int N;
    cin >> N;
    vector<int> p(N);
    for (int i = 0; i < N; i++) {
        cin >> p[i];
    }

    int S = 2*N, T = S + 1;
    V = T + 1;
    for (int i = 0; i < N; i++) {        
        add_edge(S, i, 1, 0);
        add_edge(i + N, T, 1, 0);
        for (int j = 0; j < N; j++) {
            if (p[i]-1 != j) {
                add_edge(i, j + N, 1, (p[i]) * abs(i - j));
            }
        }
    }
    cout << min_cost_flow(S, T, N) << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3456
final_rank: 2