Submission #1091185

#TimeUsernameProblemLanguageResultExecution timeMemory
1091185yogesh_saneGroup Photo (JOI21_ho_t3)C++17
100 / 100
3623 ms135360 KiB
#include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <queue> using namespace std; int n; int const inf = 1e9; vector<int>a, idx; vector<int>cost; int total_cost; vector<vector<int>>left_num, right_num; void precalc_cost(){ left_num.resize(n+1); right_num.resize(n+1); for(int i = 1; i <= n; i++){ for(int j = i+1; j <=n; j++){ left_num[a[j]].push_back(a[i]); } } for(int i = n; i >= 1; i--){ for(int j = i-1; j >= 1; j--){ right_num[a[j]].push_back(a[i]); } } for(int i = 1; i <= n; i++){ sort(left_num[i].begin(), left_num[i].end()); sort(right_num[i].begin(), right_num[i].end()); } } int query(vector<int> &v, int l, int r){ if(l > r) return 0; //numbers less than or equal to r int num_r = lower_bound(v.begin(), v.end(), r+1)-v.begin(); //numbers less than l int num_l = lower_bound(v.begin(), v.end(),l)-v.begin(); return num_r-num_l; } int query_left(int num, int l, int r){ return query(left_num[num], l, r); } int query_right(int num, int l, int r){ return query(right_num[num], l, r); } void calculate_cost(int val){ vector<int>p(n+1); // iota(p.begin(), p.end(), 0); // reverse(p.begin()+1, p.begin()+val+1); // for(int i = val; i >= 1; i--){ // int inv = 0; // for(int j = i+1; j <= n; j++){ // if((p[i] < p[j] && idx[i] > idx[j]) || // (p[i] > p[j] && idx[i] < idx[j])) // inv++; // } // cost.push_back(inv); // total_cost += inv; // } iota(p.begin(), p.end(), 0); reverse(p.begin()+1, p.begin()+val+1); int inv = 0; for(int i = val; i >= 1; i--){ inv += query_left(i, val+1, n); inv += query_right(i, i+1, val); cost.push_back(inv); total_cost += inv; } } int main(){ cin >> n; a.resize(n+1); idx.resize(n+1); vector<int>dp(n+1, inf); for(int i = 1; i <= n; i++){ cin >> a[i]; idx[a[i]] = i; } precalc_cost(); dp[0] = 0; for(int i = 1; i <= n; i++){ calculate_cost(i); for(int j = 1; j <= i; j++){ // dp[i] = min(dp[i], dp[j-1] + total_cost); // total_cost -= cost.back(); dp[i] = min(dp[i], dp[j-1] + cost.back()); cost.pop_back(); } } cout << dp[n] << '\n'; return 0; }
#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...