結果

問題 No.270 next_permutation (1)
ユーザー koyumeishikoyumeishi
提出日時 2015-08-22 00:02:17
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,894 bytes
コンパイル時間 794 ms
コンパイル使用メモリ 75,908 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-25 15:40:06
合計ジャッジ時間 2,019 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 AC 3 ms
4,384 KB
testcase_02 AC 2 ms
4,384 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,384 KB
testcase_05 AC 3 ms
4,384 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,384 KB
testcase_09 AC 8 ms
4,380 KB
testcase_10 AC 62 ms
4,380 KB
testcase_11 AC 63 ms
4,380 KB
testcase_12 AC 63 ms
4,380 KB
testcase_13 AC 60 ms
4,384 KB
testcase_14 AC 59 ms
4,380 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<int>& p, vector<int>& 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 0;
}


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

int main(){
	int n,k;
	cin >> n >> k;
	vector<int> 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;

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

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