Codeforces Round #624 (Div. 3)B. WeirdSort

B. WeirdSort

题目链接-B. WeirdSort
在这里插入图片描述
在这里插入图片描述
题目大意
给你含n个数的数组a[]和一个大小为m的p[]数组,你可以交换任意相邻a[i]和a[i+1],前提是 i 需要在p数组中,问你是否能通过此交换规则使这n个数升序排列

解题思路
模拟冒泡排序过程看最后数组里的数是否有序即可
判断有序的时候我是用一个b[]数组存排好序的数列,再与a[]数组对照,其实C++ STL里有一个封装好的函数is_sorted,可以直接判断数组是否有序

总结一下
is_sorted()函数是测试范围内的元素是否已经有序,使用operator<或者comp来进行比较,如果范围内的元素个数少于两个,总是返回true.

is_sorted_until()返回第一个破坏序列有序的元素迭代器,也是使用operator<或者comp来进行比较

附上代码

#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
using namespace std;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+5;
typedef long long ll;
typedef pair<int,int> PII;
int a[110],p[110],b[110];
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	
	int t;
	cin>>t;
	while(t--){
		int n,m;
		bool flag=1;
		cin>>n>>m;
		for(int i=1;i<=n;i++){
			cin>>a[i];
			b[i]=a[i];
		}
		for(int i=1;i<=m;i++){
			cin>>p[i];
		}
		sort(b+1,b+1+n);
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				if(a[p[j]+1]<a[p[j]]){
					swap(a[p[j]+1],a[p[j]]);
				}
			}
		}
		for(int i=1;i<=n;i++){
			if(a[i]!=b[i]){
				flag=0;
				break;
			}
		}
		if(flag)//if(is_sorted(a+1,a+m+1)),可起到flag的作用
			cout<<"YES"<<endl;
		else
			cout<<"NO"<<endl;
	}
	return 0;
}


发布了78 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/104501610