結果

問題 No.270 next_permutation (1)
ユーザー koyumeishikoyumeishi
提出日時 2015-08-22 02:10:34
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 66 ms / 2,000 ms
コード長 1,200 bytes
コンパイル時間 604 ms
コンパイル使用メモリ 81,704 KB
実行使用メモリ 5,016 KB
最終ジャッジ日時 2023-08-23 06:59:17
合計ジャッジ時間 1,852 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 3 ms
4,376 KB
testcase_05 AC 3 ms
4,380 KB
testcase_06 AC 3 ms
4,380 KB
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 8 ms
4,376 KB
testcase_10 AC 64 ms
4,912 KB
testcase_11 AC 62 ms
5,016 KB
testcase_12 AC 66 ms
4,908 KB
testcase_13 AC 60 ms
4,892 KB
testcase_14 AC 61 ms
5,004 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cstdio>
#include <sstream>
#include <map>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
#include <set>
using namespace std;

struct unko{
	long long val;
	bool operator < (const unko& y) const {
		return val < y.val;
	}
};

vector<unko> p;
vector<long long> b;
vector<int> pos;
long long v;

void swap(unko& s, unko& t){
	int x = pos[s.val];
	int y = pos[t.val];
	v -= abs(p[x].val - b[x]);
	v -= abs(p[y].val - b[y]);
	
	swap(p[x].val, p[y].val);
	swap(pos[s.val], pos[t.val]);

	v += abs(p[x].val - b[x]);
	v += abs(p[y].val - b[y]);
}

long long func(vector<unko>& p, vector<long long>& b){
	int n = p.size();
	long long ret = 0;
	for(int i=0; i<n; i++){
		ret += abs(p[i].val - b[i]);
	}
	return ret;
}

#include <cassert>

int main(){
	int n,k;
	cin >> n >> k;
	p.resize(n);
	b.resize(n);
	pos.resize(n+1);

	for(int i=0; i<n; i++){
		cin >> p[i].val;
		pos[p[i].val] = i;
	}
	for(int i=0; i<n; i++){
		cin >> b[i];
	}

	if(k==0){
		cout << 0 << endl;
		return 0;
	}

	v = func(p,b);
	long long ans = v;

	for(int i=1; i<k; i++){
		next_permutation(p.begin(), p.end());
		ans += v;
	}

	cout << ans << endl;
	return 0;
}
0