結果

問題 No.270 next_permutation (1)
ユーザー kyuridenamidakyuridenamida
提出日時 2015-08-22 00:50:57
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 63 ms / 2,000 ms
コード長 912 bytes
コンパイル時間 1,797 ms
コンパイル使用メモリ 148,236 KB
実行使用メモリ 4,736 KB
最終ジャッジ日時 2023-08-23 06:59:02
合計ジャッジ時間 2,396 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;




long long sum = 0;
vector<long long> p,B;
void f(vector<long long> &p){
	for(int i = p.size() - 1 ; i > 0 ; i--){
		if( p[i] > p[i-1] ){
			for(int j = i - 1 ; j < p.size() ; j++) sum -= abs(p[j]-B[j]);
			int x = -1;
			for(int j = i ; j < p.size() ; j++)
				if( p[i-1] < p[j] && (x==-1||p[x] > p[j]) ) x = j;
			swap(p[i-1],p[x]);
			reverse(p.begin()+i,p.end());
			for(int j = i - 1 ; j < p.size() ; j++) sum += abs(p[j]-B[j]);
			return;
		}
	}
	sum = 0;
	reverse(p.begin(),p.end());
	for(int i = 0 ; i < p.size() ; i++) sum += abs(p[i]-B[i]);
}

int main(){
	int N,K;
	cin >> N >> K;
	p.resize(N);
	B.resize(N);
	for(int i = 0 ; i < N ; i++) cin >> p[i];
	for(int i = 0 ; i < N ; i++) cin >> B[i];
	for(int i = 0 ; i < N ; i++)
		sum += abs(p[i]-B[i]);
	
	long long ans = 0;
	for(int i = 0 ; i < K ; i++){
		ans += sum;
		f(p);
	}
	cout << ans << endl;
}
0