题目
题意:给定长度为
n
n
n的排列
a
a
a,在所有
i
<
j
,
a
i
>
a
j
i<j,a_i>a_j
i<j,ai>aj的点对
(
i
,
j
)
(i,j)
(i,j)中建立无向边。问最后得到的逆序图中,有多少个连通块。
思路:对于当前的点 x x x,后边任意小于 x x x的点 y y y,都和 x x x相连。因此,我们可以维护一个递增的单调栈 s t a c k stack stack。此外,对于当前点 c c c,如果 s t a c k [ p o s 1 ] < c < s t a c k [ p o s 2 ] stack[pos1]<c<stack[pos2] stack[pos1]<c<stack[pos2],那么说明 p o s 1 + 1 , p o s 1 + 2 , . . . , p o s 2 pos1+1,pos1+2,...,pos2 pos1+1,pos1+2,...,pos2都和点 c c c相连,它们属于同个连通块,我们需要把它们合并。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 200010;
int n, ans[maxn];
void solve() {
scanf("%d", &n);
int cur = 0, tot = 0, x;
for (int i = 0; i < n; ++i) {
scanf("%d", &x);
if (cur < x) {
cur = x;
ans[tot++] = x;
} else {
while (tot > 1 && ans[tot-2] > x) {
ans[tot-2] = ans[tot-1];
--tot;
}
}
}
printf("%d\n", tot);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
solve();
}
}