Description
有一个 1 ∼ n 1\sim n 1∼n 的排列,给定 n − 1 n-1 n−1 个大于号或小于号描述相邻两个数的大小关系。请你构造两个符合要求的排列,分别满足 LIS 最短和 LIS 最长。LIS : 最长上升子序列。
1 ≤ n ≤ 2 × 1 0 5 1 \leq n \leq 2 \times 10^5 1≤n≤2×105。
Solution
考虑最短的 LIS。因为小于号产生的上升是不可避免的,所以让大于号产生的尽可能短。所以先让排列为 n , n − 1 , ⋯ , 2 , 1 n,n-1, \cdots ,2,1 n,n−1,⋯,2,1。对于一段连续的小于号翻转对应的区间。最长的 LIS 同理,让排列为 1 , 2 , ⋯ , n − 1 , n 1,2,\cdots,n-1,n 1,2,⋯,n−1,n,对于一段连续的大于号翻转对应的区间。
时空复杂度为 O ( n ) O(n) O(n)。
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
inline int read() {
int x = 0, f = 0; char ch = 0;
while (!isdigit(ch)) f |= ch == '-', ch = getchar();
while (isdigit(ch)) x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
char s[N];
int a[N];
int main() {
int T = read();
while (T--) {
int n = read(); scanf("%s", s + 1);
for (int i = 1; i <= n; i++) a[i] = n - i + 1;
for (int i = 1; i < n; i++) {
int l = i;
while (s[i] == '<') i++;
reverse(a + l, a + i + 1);
}
for (int i = 1; i <= n; i++) printf("%d ", a[i]); puts("");
for (int i = 1; i <= n; i++) a[i] = i;
for (int i = 1; i < n; i++) {
int l = i;
while (s[i] == '>') i++;
reverse(a + l, a + i + 1);
}
for (int i = 1; i <= n; i++) printf("%d ", a[i]); puts("");
}
return 0;
}