結果

問題 No.271 next_permutation (2)
ユーザー sugim48sugim48
提出日時 2015-08-21 23:21:55
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 1,645 bytes
コンパイル時間 711 ms
コンパイル使用メモリ 82,888 KB
実行使用メモリ 12,480 KB
最終ジャッジ日時 2023-09-25 15:27:15
合計ジャッジ時間 7,131 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#define _USE_MATH_DEFINES
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
 
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<ll, int> ll_i;
typedef pair<double, int> d_i;
typedef pair<ll, ll> ll_ll;
typedef pair<double, double> d_d;
struct edge { int u, v; ll w; };
 
ll MOD = 1000000007;
ll _MOD = 1000000009;
double EPS = 1e-10;
int INF = INT_MAX / 10;

struct bit {
	vector<ll> v;
	bit(int n) : v(n + 1) {}
	ll sum(int i) {
		ll res = 0;
		for (; i > 0; i -= i & -i) res += v[i];
		return res;
	}
	void add(int i, ll x) {
		for (i++; i < v.size(); i += i & -i) v[i] += x;
	}
};

int main() {
	int N, K; cin >> N >> K;
	vector<int> p(N), B(N);
	for (int i = 0; i < N; i++)
		scanf("%d", &B[i]);
	ll ans = 0, sum = 0;
	bit b(N);
	for (int i = 0; i < N; i++) {
		sum += i - b.sum(B[i] - 1);
		b.add(B[i] - 1, 1);
	}
	while (K--) {
		ans += sum;
		int i;
		for (i = N - 2; i >= 0 && B[i] > B[i + 1]; i--);
		if (i == -1) {
			sum = 0;
			sort(B.begin(), B.end());
			continue;
		}
		int n = N - i - 1;
		sum -= (ll)n * (n - 1) / 2;
		for (int j = i + 1; j < N; j++)
			if (B[i] > B[j]) sum--;
		next_permutation(B.begin(), B.end());
		for (int j = i + 1; j < N; j++)
			if (B[i] > B[j]) sum++;
		/*for (int i = 0; i < N; i++)
			cout << B[i] << ' ';
		cout << endl;
		cout << sum << endl;*/
	}
	cout << ans << endl;
}
0