【题解】CF1585D Yet Another Sorting Problem

题意

给定一个长度为 n 的数组 a
每次操作可以选择三个数进行循环右移。
询问是否可以将数组排序。

Sol

若数组中存在相同的数,那么显然有解。
再考虑没有数相同的情况。
由于是挑 3 个数循环右移,那么每次逆序对的数量会减少 2
那么统计一下逆序对即可。
我用的是树状数组。时间复杂度 O(nlogn),存在 O(n) 做法。

Code

//LYC_music yyds!
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0)
#define lowbit(x) (x&(-x))
using namespace std;
inline char gc()
{
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
int read()
{
	int pos=1,num=0;
	char ch=getchar();
	while (!isdigit(ch))
	{
		if (ch=='-') pos=-1;
		ch=getchar();
	}
	while (isdigit(ch))
	{
		num=num*10+(int)(ch-'0');
		ch=getchar();
	}
	return pos*num;
}
void write(int x)
{
	if (x<0)
	{
		putchar('-');
		write(-x);
		return;
	}
	if (x>=10) write(x/10);
	putchar(x%10+'0');
}
void writesp(int x)
{
	write(x);
	putchar(' ');
}
void writeln(int x)
{
	write(x);
	putchar('\n');
}
const int N=5e5+10;
bool vis[N],flag;
int n,a[N],tree[N];
inline void add(int x,int y)
{
	for (;x<=n;x+=lowbit(x))
		tree[x]+=y;
}
inline int query(int x)
{
	int res=0;
	for (;x;x-=lowbit(x))
		res+=tree[x];
	return res;
}
signed main()
{
	int T=read();
	while (T--)
	{
		n=read(); flag=0;
		for (int i=1;i<=n;i++)
			vis[i]=0,tree[i]=0;
		for (int i=1;i<=n;i++)
		{
			a[i]=read();
			if (vis[a[i]]) flag=1;
			vis[a[i]]=1;
		}
		if (flag)
		{
			puts("YES");
			continue;
		}
		int res=0;
		for (int i=1;i<=n;i++)
		{
			res+=query(n)-query(a[i]);
			add(a[i],1);
		}
		if (res&1) puts("NO");
		else puts("YES");
	}
}




posted @   dd_d  阅读(97)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示
主题色彩