标签:case force 序列 initial pen org main final HERE
You are given an array aa of length nn .
You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm , where 1≤pi<n1≤pi<n . The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1] . You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤?≤ana1≤a2≤?≤an ) using only allowed swaps.
For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2] , then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp ). We get the array a=[3,1,2]a=[3,1,2] . Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp ). We get the array a=[1,3,2]a=[1,3,2] . Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3] , sorted in non-decreasing order.
You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.
You have to answer tt independent test cases.
The first line of the input contains one integer tt (1≤t≤1001≤t≤100 ) — the number of test cases.
Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100 ) — the number of elements in aa and the number of elements in pp . The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100 ). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n , all pipi are distinct) — the set of positions described in the problem statement.
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤?≤ana1≤a2≤?≤an ) using only allowed swaps. Otherwise, print "NO".
6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4
YES NO YES YES NO YES
大意是给定序列a和p,通过一定次数的交换操作(只能swap(a[p[i]],a[p[i]+1]))能否让a序列单调不减。可以这么想,因为每次只能交换相邻两个数,所以当一个数要到达最终排序好的位置的话,肯定是一步一步挪过去的,自然想到冒泡,根据题意这里选择从前往后把大的数交换到后面,每次需要swap的时候,先检查下标是否在p数组里。理论上可以sort一遍p数组然后二分,但是看到数据量这么小直接O(n)检查也能过。
#include <bits/stdc++.h> using namespace std; int a[105],p[105]; int n,m; int main() { int t; cin>>t; while(t--) { cin>>n>>m; int i,j,k; bool flag=1; for(i=1;i<=n;i++) { scanf("%d",&a[i]); } for(i=1;i<=m;i++) { scanf("%d",&p[i]); } for(i=1;i<=n-1;i++) { for(j=1;j<=n-i;j++) { if(a[j]>a[j+1]) { int find=0; for(k=1;k<=m;k++) { if(p[k]==j) { int t=a[j]; a[j]=a[j+1]; a[j+1]=t; find=1; break; } } if(!find) { flag=0; goto label; } } } } label:; if(!flag) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; } } return 0; }
Codeforces Round #624 (Div. 3) B. WeirdSort(排序)
标签:case force 序列 initial pen org main final HERE
原文地址:https://www.cnblogs.com/lipoicyclic/p/12373613.html