結果

問題 No.270 next_permutation (1)
ユーザー koyumeishikoyumeishi
提出日時 2015-08-22 00:09:00
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 64 ms / 2,000 ms
コード長 2,044 bytes
コンパイル時間 1,942 ms
コンパイル使用メモリ 76,684 KB
実行使用メモリ 4,756 KB
最終ジャッジ日時 2023-08-22 23:30:43
合計ジャッジ時間 2,784 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,380 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 8 ms
4,376 KB
testcase_10 AC 63 ms
4,692 KB
testcase_11 AC 64 ms
4,584 KB
testcase_12 AC 64 ms
4,756 KB
testcase_13 AC 61 ms
4,612 KB
testcase_14 AC 60 ms
4,688 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;

ostream& operator << (ostream& os, vector<int>& v){
	for(int i=0; i<v.size(); i++){
		os << v[i] << " ";
	}
	return os;
}


long long my_permutation(vector<long long>& p, vector<long long>& b, long long last)
{
	int n = p.size();
	if(n == 1){
		return 0;
	}

    int i = n-1;

    for(;;)
    {
        int ii = i;
        --i;
        if (p[i] < p[ii])
        {
            int j = n;
            while (!(p[i] < p[--j]))
            {}

        	last -= abs(p[i] - b[i]);
        	last -= abs(p[j] - b[j]);

            swap(p[i], p[j]);
            last += abs(p[i] - b[i]);
            last += abs(p[j] - b[j]);

            for(int k=ii; k<n; k++){
            	last -= abs(p[k] - b[k]);
            }
            reverse(p.begin()+ii, p.end());

            for(int k=ii; k<n; k++){
            	last += abs(p[k] - b[k]);
            }

            return last;
        }
        if (i == 0)
        {
            for(int k=0; k<n; k++){
            	last -= abs(p[k] - b[k]);
            }
            reverse(p.begin(), p.end());

            for(int k=0; k<n; k++){
            	last += abs(p[k] - b[k]);
            }
            return last;
        }
    }
    return last;
}


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

#include <cassert>

int main(){
	int n,k;
	cin >> n >> k;
	vector<long long> p(n), b(n);
	for(int i=0; i<n; i++){
		cin >> p[i];
	}
	for(int i=0; i<n; i++){
		cin >> b[i];
	}

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

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

	if(n == 1){
		for(int i=1; i<k; i++){
			ans += val;
		}
		cout << ans << endl;
		return 0;
	}

	for(int i=1; i<k; i++){
		val = my_permutation(p,b, val);
		ans += val;
	}

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