Inversion Graph(图论/思维/单调栈)

题目
题意:给定长度为 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();
	} 
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值