[CF] B. Find the Permutation - Codeforces Round 997 (Div. 2)

https://codeforces.com/contest/2056/problem/B

题目大意

给出一个 $n (n \le 1000)$ 长的未知排列和已知的 $n$ 个点的图,如果在排列中 $1 \le i < j \le n$ 且 $p_i < p_j$,则图上有一条 $<p_i, p_j>$ 的无向边。邻接矩阵的形式给出图,问排列是什么。

简要题解

直接看 $1$ 放在排列的什么位置。因为 $1$ 比所有元素都小,因此其右侧有 $x$ 个数,就会有 $x$ 条边,它就是从右数的,第 $x + 1$ 个数。

因此我们只要从小往大填。对于 $i$,如果前面的数都填好了,则我们只看 $x$ 到 $[x + 1, n]$ 的边,这样的边有 $y$ 条,则 $i$ 填在现在空格的右数 $y + 1$ 个位置。

复杂度

$T$:$O(n ^ 2)$

$S$:$O(n ^ 2)$ 因为要存邻接矩阵,当然如果不存的话也可以做到 $O(n)$,只是没必要(至少要存结果)。

代码实现

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

int io_=[](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();

using LL = long long;
using ULL = unsigned long long;
using LD = long double;
using PII = pair<int, int>;
using VI = vector<int>;
using MII = map<int, int>;

template<typename T> void cmin(T &x,const T &y) { if(y<x) x=y; }
template<typename T> void cmax(T &x,const T &y) { if(x<y) x=y; }
template<typename T> bool ckmin(T &x,const T &y) { 
    return y<x ? (x=y, true) : false; }
template<typename T> bool ckmax(T &x,const T &y) { 
    return x<y ? (x=y, true) : false; }
template<typename T> void cmin(T &x,T &y,const T &z) {// x<=y<=z 
    if(z<x) { y=x; x=z; } else if(z<y) y=z; }
template<typename T> void cmax(T &x,T &y,const T &z) {// x>=y>=z
    if(x<z) { y=x; x=z; } else if(y<z) y=z; }

// mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
// mt19937_64 rnd_64(chrono::system_clock::now().time_since_epoch().count());

/*
---------1---------2---------3---------4---------5---------6---------7---------
1234567890123456789012345678901234567890123456789012345678901234567890123456789
*/

void solve() {
  int n; cin >> n;
  vector<string> g(n);
  for (int i = 0; i < n; i++) {
    cin >> g[i];
  }

  vector<int> p(n);
  for (int i = 1; i <= n; i++) {
    int cnt = 1;
    for (int j = i; j <= n; j++) {
      cnt += (g[i - 1][j] == '1');
    }

    for (int j = n - 1; j >= 0; j--) {
      if (p[j]) continue;
      if (!--cnt) {
        p[j] = i;
        break;
      }
    }
  }

  for (int i = 0; i < n; i++) {
    cout << p[i] << (" \n"[i == n - 1]);
  }
}

int main() {
  int t = 1; 
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
Prev: [CF] D. Almost Identity Permutations - Educational Codeforces Round 32
Next: [CF] C. Palindromic Subsequences - Codeforces Round 997 (Div. 2)