結果

問題 No.270 next_permutation (1)
ユーザー pekempeypekempey
提出日時 2017-01-19 16:05:00
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 26 ms / 2,000 ms
コード長 1,510 bytes
コンパイル時間 579 ms
コンパイル使用メモリ 72,340 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-24 17:13:53
合計ジャッジ時間 2,332 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 2 ms
4,384 KB
testcase_02 AC 3 ms
4,376 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,384 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 4 ms
4,376 KB
testcase_10 AC 25 ms
4,376 KB
testcase_11 AC 25 ms
4,380 KB
testcase_12 AC 26 ms
4,376 KB
testcase_13 AC 24 ms
4,380 KB
testcase_14 AC 24 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
	int n, K;
	cin >> n >> K;

	vector<int> a(n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}

	long long d = 0;

	vector<int> b(n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &b[i]);
		d += abs(b[i] - a[i]);
	}

	long long ans = 0;

	while (K--) {
		ans += d;

		// next_permutation
		// 正当性は明らかなので、計算量解析だけおこなう。
		// 
		// 解析にはポテンシャルを用いる。
		// ポテンシャル関数は "Φ:=a[i]>a[i+1] となる i の総数"と定義する。
		// 
		// #1の while が回った回数を X とする。
		// このとき、⊿Φ=1-Xである。なぜなら、
		// #2のswapによりΦは+1、
		// #3のreverseによりΦは-Xするからである。
		//
		// ならしコストは、(whileが回った回数)+(ポテンシャルの変化量)とみなせるので、
		// ならしコストは X+(1-X)=1 となる。

		// #1
		int i = n - 2;
		while (i >= 0 && a[i] >= a[i + 1]) i--;

		if (i == -1) {
			reverse(a.begin(), a.end());
			d = 0;
			for (int i = 0; i < n; i++) {
				d += abs(b[i] - a[i]);
			}
			continue;
		}

		int j = i + 1;
		while (j + 1 < n && a[j + 1] > a[i]) j++;

		for (int k = i; k < n; k++) {
			d -= abs(b[k] - a[k]);
		}

		// #2
		swap(a[i], a[j]);

		// #3
		reverse(a.begin() + i + 1, a.end());

		for (int k = i; k < n; k++) {
			d += abs(b[k] - a[k]);
		}
	}

	cout << ans << endl;
}
0