結果
問題 | No.1087 転倒数の転倒数 |
ユーザー |
![]() |
提出日時 | 2020-06-19 23:28:15 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 155 ms / 2,000 ms |
コード長 | 2,889 bytes |
コンパイル時間 | 2,559 ms |
コンパイル使用メモリ | 203,760 KB |
最終ジャッジ日時 | 2025-01-11 08:06:12 |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 6 |
other | AC * 31 |
ソースコード
#include <bits/stdc++.h>using namespace std;#ifdef LOCAL#include "debug.h"#else#define DEBUG(...)#endiftemplate <class T> struct fenwick {int n;vector<T> t;fenwick(int _n = -1) : n(_n), t(n + 1) {}void add(int i, T a) { for (++i; i <= n; i += i & -i) t[i] += a; }T sum(int i) const {T s = 0;for (; i; i -= i & -i) s += t[i];return s;}T sum(int l, int r) const { return sum(r) - sum(l); }int kth(T k) const {int i = 0;for (int w = 1 << __lg(n); w; w >>= 1)if (i + w <= n and t[i + w] <= k) k -= t[i += w];return i;}};int main() {cin.tie(nullptr);ios::sync_with_stdio(false);auto f = [](int n, int x) {vector<int> ord(n), a(n);for (int i = 0; i < n; ++i) {int t = min(x, i);ord[i] = i - t;x -= t;}fenwick<int> ft(n);for (int i = 0; i < n; ++i) {ft.add(i, 1);}for (int i = n; i--; ) {a[i] = ft.kth(ord[i]);ft.add(a[i], -1);}return a;};int n, k;cin >> n >> k;if (k > n * (n - 1)) {cout << "No\n";exit(0);}cout << "Yes\n";if (k <= n * (n - 1) / 2) {auto row = f(n, k);for (int i = 0; i < n; ++i) {auto a = f(n, row[i]);for (int j = 0; j < n; ++j) {cout << i * n + a[j] << " \n"[j == n - 1];}}exit(0);}if (n < 4) {vector<int> p(n * n);iota(begin(p), end(p), 0);do {vector a(n, vector<int>(n));vector<int> row(n), col(n);for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {a[i][j] = p[i * n + j];}for (int y = 0; y < n; ++y) {for (int x = 0; x < y; ++x) {row[i] += a[i][x] > a[i][y];}}}for (int j = 0; j < n; ++j) {for (int y = 0; y < n; ++y) {for (int x = 0; x < y; ++x) {col[j] += a[x][j] > a[y][j];}}}int t = 0;for (int y = 0; y < n; ++y) {for (int x = 0; x < y; ++x) {t += row[x] > row[y];t += col[x] > col[y];}}if (t == k) {for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {cout << a[i][j] << " \n"[j == n - 1];}}break;}} while (next_permutation(begin(p), end(p)));exit(0);}k -= n * (n - 1) / 2;auto row = f(n, k);for (int i = 0; i < n; ++i) {row[i] -= n - i - 1;}int mn = *min_element(begin(row), end(row));for (auto&& e : row) {e -= mn;}for (int i = 0; i < n; ++i) {auto a = f(n - 1, row[i]);for (int j = 0; j < n; ++j) {int cur = 0;if (j < n - i - 1) {cur = i * n + a[j] + 1;} else if (j > n - i - 1) {cur = i * n + a[j - 1] + 1;}cout << cur << " \n"[j == n - 1];}}}