P7714 「EZEC-10」排列排序-双指针

题目

前言

如果按照左右逼近的话 是一定会多算的,造成代价更大 ,所以不行。

题目思路

注意审题 对于1-n的每一个i都有pi=i
所以在遍历的时候 发现不符合的就可以定一个指针卡住,另一个指针往后走,找到正确的位置,区间就是代价。
但是这个左指针在往后寻找的过程中必须时刻更新区间最大的值,而不是最早的那个值不更新,直接上代码吧 左指针初始就是右指针+1,这一步也要更新

#include <iostream>
using namespace std;
int a[1000005];
void solve() {
	int n;
	cin >> n;
	long long ans = 0;
	int head = 1;
	int tail;
	for (int i = 1; i <= n; i++)cin >> a[i];
	while (head <= n) {
		if (a[head] == head) {
			head++;
			continue;
		} else {
			int maxn = a[head];
			tail = head + 1;
			maxn = max(maxn, a[tail]);
			while (maxn > tail) {
				tail++;
				maxn = max(maxn, a[tail]);
			}
			ans += tail - head + 1;
			head = tail + 1;
		}
	}
//我的思路尾部往前找到不同直接ans+如果中间对的序列也会被加 答案变大了
//	 4 2 3 1
	//单纯左右逼近绝对会多算
//	 4 2 1 3
//	 1 4 5 6 3 2
//
	cout << ans << endl;
	return ;
}
int main() {

	int t;
	cin >> t;
	while (t--)solve();


	return 0;
}
posted @ 2025-04-16 20:22  LteShuai  阅读(26)  评论(0)    收藏  举报