Educational Codeforces Round 109 (Rated for Div. 2)–D--Armchairs
DP
#include<bits/stdc++.h>
using namespace std;
template <typename T> void debug(string s, T x) { cout << s << "=" << x << "\n"; }
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
const ll N = 1e5 + 5;
const ll MOD = 1e9 + 7;
const ll INF = 0x7fffffff;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n; cin >> n;
vector<int> a, b;
for (int i = 0; i < n;i++) {
int x; cin >> x;
if (x == 1) a.push_back(i);
else b.push_back(i);
}
int bn = b.size();
int an = a.size();
vector<vector<int>> dp(bn + 1, vector<int>(an + 1, 1e9));
dp[0][0] = 0;
for (int i = 0; i < bn; i++) {
dp[i + 1][0] = 0;
for (int j = 1; j <= an; ++j) {
int x = a[j - 1];
int y = b[i];
dp[i + 1][j] = min(dp[i][j], dp[i][j - 1] + abs(x - y));
}
}
cout << dp[bn][an] << '\n';
return 0;
}