Penchick and his friend Kohane are touring Indonesia, and their next stop is in…
- User
Penchick and his friend Kohane are touring Indonesia, and their next stop is in Surabaya!
In the bustling food stalls of Surabaya, Kohane bought n satay sticks and arranged them in a line, with the i -th satay stick having length pi . It is given that p is a permutation∗ of length n .
Penchick wants to sort the satay sticks in increasing order of length, so that pi=i for each 1≤i≤n . For fun, they created a rule: they can only swap neighboring satay sticks whose lengths differ by exactly 1 . Formally, they can perform the following operation any number of times (including zero):
Select an index i (1≤i≤n−1 ) such that |pi+1−pi|=1 ; Swap pi and pi+1 . Determine whether it is possible to sort the permutation p , thus the satay sticks, by performing the above operation
i #include<bits/stdc++.h> using namespace std; string calc(int n,vector&v) { bool sorted=false; int count=0; while(!sorted) { if(count>n) break; for(int i=0;i<n-1;i++) { if(v[i]-v[i+1]==1){ swap(v[i],v[i+1]); } } for(int i=0;i<n-1;i++) { if(v[i+1]<v[i]){ sorted=false; break; } sorted=true; } count++; }
if(sorted) return "YES"; else return "NO";} void process_test_case() { int n=0; cin>>n; vector v(n,0); for(int i=0;i<n;i++) cin>>v[i]; cout<<calc(n,v)<<endl; }
int main() { int T; cin >> T;
while (T--) { process_test_case(); } return 0;}
is the logic of given code correct
- Assistant
The logic in the provided code is incorrect for the following reasons:
Problem Overview
- Objective: Sort a permutation
pof lengthninto increasing order (p[i] = ifor each1 ≤ i ≤ n) by swapping only neighboring elements that differ by in value.
- Objective: Sort a permutation