Submission #445262

#TimeUsernameProblemLanguageResultExecution timeMemory
445262maomao90Group Photo (JOI21_ho_t3)C++17
100 / 100
912 ms596 KiB
#include <bits/stdc++.h> 
using namespace std;

template <class T>
inline bool mnto(T& a, T b) {return a > b ? a = b, 1 : 0;}
template <class T>
inline bool mxto(T& a, T b) {return a < b ? a = b, 1: 0;}
#define REP(i, s, e) for (int i = s; i < e; i++)
#define RREP(i, s, e) for (int i = s; i >= e; i--)
typedef long long ll;
typedef long double ld;
#define MP make_pair
#define FI first
#define SE second
typedef pair<int, int> ii;
typedef pair<ll, ll> pll;
#define MT make_tuple
typedef tuple<int, int, int> iii;
#define ALL(_a) _a.begin(), _a.end()
#define pb push_back
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ii> vii;

#ifdef DEBUG
#define debug(args...) _debug(args)
void _debug(const char* format, ...) {
	va_list args;
	va_start(args, format);
	vprintf(format, args);
	va_end(args);
}
#else
#define debug(args...)
#endif

#define INF 1000000005
#define LINF 1000000000000000005
#define MOD 1000000007
#define MAXN 5005

int n;
int h[MAXN];
int mp[MAXN];
int dp[MAXN]; // minimum number of swaps with heights [1 ... i]

int fw1[MAXN], fw2[MAXN];
void incre(int i, int x, int* fw) {
	for (; i <= n; i += i & -i) fw[i] += x;
}
int qsm(int i, int* fw) {
	int res = 0;
	for (; i > 0; i -= i & -i) res += fw[i];
	return res;
}
int qsm(int s, int e, int* fw) {
	return qsm(e, fw) - qsm(s - 1, fw);
}

int main() {
	scanf("%d", &n);
	REP (i, 1, n + 1) {
		scanf("%d", &h[i]);
		mp[h[i]] = i;
	}
	dp[1] = 0;
	REP (i, 2, n + 1) {
		dp[i] = INF;
		memset(fw1, 0, sizeof fw1);
		memset(fw2, 0, sizeof fw2);
		REP (j, 1, i + 1) {
			incre(mp[j], 1, fw1);
		}
		int cost = 0;
		RREP (j, i, 1) {
			cost -= qsm(1, mp[j] - 1, fw2) * 2;
			cost += i - j;
			cost += qsm(mp[j] + 1, n, fw1);
			// consider placing i at position j, so before position j, minimum
			// swaps is dp[j - 1] and after position j, the array is 
			// [i, i - 1, i - 2, ..., j]
			mnto(dp[i], dp[j - 1] + cost);
			incre(mp[j], -1, fw1);
			incre(mp[j], 1, fw2);
		}
	}
	printf("%d\n", dp[n]);
	return 0;
}

/*
5
3 5 2 4 1
*/

Compilation message (stderr)

Main.cpp: In function 'int main()':
Main.cpp:61:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
   61 |  scanf("%d", &n);
      |  ~~~~~^~~~~~~~~~
Main.cpp:63:8: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
   63 |   scanf("%d", &h[i]);
      |   ~~~~~^~~~~~~~~~~~~
#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...