jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        map.entry(x).and_modify(|e| *e += 1).or_insert(1);
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v.iter() {
        let val = map[i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}
//  [rust]
use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        *map.entry(x).or_insert(0) += 1;
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v.iter() {
        let val = map[i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}
//  [rust]
use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        *map.entry(x).or_insert(0) += 1;
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v {
        let val = map[&i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}
//  [swift]
import Foundation
let N = Int(String(readLine()!))!
let nums = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var table: [Int: Int] = [:]
var sum = 0
for n in nums {
  table[n] = (table[n] ?? 0) + 1
}
for (key, value) in table {
  sum += value * (value - 1) / 2
}
for n in nums {
  print(sum - table[n]! + 1)
}
//  [swift]
import Foundation

/*
// 1
let N = Int(readLine()!)!

// 1 2
let split = readLine()!.componentsSeparatedByString(" ")
let N = Int(split[0])!
let S = Int(split[1])!

// 1 2 3 4 5
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
*/

let N = Int(readLine()!)!
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var dic = [Int: Int]()
var answer = 0
for e in array { 
  if dic[e] != nil {
    dic[e] = dic[e]! + 1
  } else {
    dic[e] = 1
  }
  answer += dic[e]! - 1
}

for e in array {
  print(answer - dic[e]! + 1 )
}
//  [swift]
import Foundation

/*
// 1
let N = Int(readLine()!)!

// 1 2
let split = readLine()!.componentsSeparatedByString(" ")
let N = Int(split[0])!
let S = Int(split[1])!

// 1 2 3 4 5
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
*/

let N = Int(readLine()!)!
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var dic = [Int: Int]()
for e in array { 
  if dic[e] != nil {
    dic[e] = dic[e]! + 1
  } else {
    dic[e] = 1
  }
}
for e in array {
  var answer = 0
  for f in dic {
    var endIndex = f.1
    if e == f.0 { endIndex -= 1 }
    for g in 0 ..< endIndex {
      answer += g
    }
  }
  print(answer)
}
//  [typescript]
import * as fs from "fs";

function calcCombination(n: number) {
	return n * (n - 1) / 2;
}

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const a = input[1].split(" ").map((x: string): number => +x);

const dict: Array<number> = [];
for (const ball of a) {
	if (dict[ball] === undefined) dict[ball] = 0;
	dict[ball] += 1;
}

// pre-calc
const combinations = new Array(n + 1);
for (const value of dict) {
	if (value === undefined) continue;
	if (combinations[value] === undefined) {
		combinations[value] = calcCombination(value);
	}
	if (combinations[value - 1] === undefined) {
		combinations[value - 1] = calcCombination(value - 1);
	}
}

let all_sum = 0;
for (const value of dict) {
	if(value === undefined) continue;
	all_sum += combinations[value];
}

for (let i = 0; i < n; i++) {
	const count: number = dict[a[i]];
	const ans = all_sum - combinations[count] + combinations[count - 1];
	console.log(ans);
}
//  [typescript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});
process.stdin.on('end', function() {
    main(g_input.split(/\r?\n/));
});

// 解答
function main(inputs:Array<string>) : void {

    // ボールの総数
    const ball: number = Number.parseInt(inputs[0]);
    // ボールに記載されている整数のリスト
    const ballList: number[] = inputs[1].split(" ").map((x: string): number => +x);
    // 各整数のボールの個数
    const numList: number[] = [];
    // 各整数の組み合わせ数
    const combinations = new Array(ball + 1);
    // 全組み合わせ数
    let all_sum = 0;

    // 各整数のボールの個数計算
    for (const ball of ballList) {

        if (numList[ball] === undefined) numList[ball] = 0;
        numList[ball] += 1;
    }

    // 各整数の組み合わせ数計算
    for (const value of numList) {

        if (value === undefined) continue;

        if (combinations[value] === undefined) {

            combinations[value] = calcCombination(value);
        }

        if (combinations[value - 1] === undefined) {

            combinations[value - 1] = calcCombination(value - 1);
        }
    }

    // 全組み合わせ数合算
    for (const value of numList) {

        if(value === undefined) continue;
        all_sum += combinations[value];
    }

    for (let i = 0; i < ball; i++) {

        const count: number = numList[ballList[i]];
        const answer = all_sum - combinations[count] + combinations[count - 1];
        console.log(answer);
    }
}

// 組み合わせ計算
function calcCombination(num: number) {

	return num * (num - 1) / 2;
}
//  [typescript]
export class Main {
  static main(input: string): void {
    const tmp: string[] = input.split("\n");
    const [n]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const a: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const map = {};
    for (let i = 0; i < n; i++) {
      const ai = a[i];
      if (map[ai] == null) {
        map[ai] = 1;
      } else {
        map[ai] = map[ai] + 1;
      }
    }
    const keys = Object.keys(map);
    let all = 0;
    const minusMap = {};
    for (let i = 0, len = keys.length; i < len; i++) {
      const value = map[keys[i]];
      const count = value * (value - 1) / 2;
      all += count;
      minusMap[keys[i]] = count - (value - 1) * (value - 2) / 2;
    }
    for (let i = 0; i < n; i++) {
      console.log(all - minusMap[a[i]]);
    }
  }
}
Main.main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
function main(input) {
  const inputs =input.split('\n')
  const [N] = inputs[0].split(' ').map(Number)
  const A = inputs[1].split(' ').map(Number)

  const count = []
  for(let i = 0; i < N; i++) {
    if (count[A[i]] === undefined) {
      count[A[i]] = 0
    }
    count[A[i]] = count[A[i]] + 1
    // console.log(count)
  }

  // console.log(count)
  for(let i = 0; i <= N - 1; i++) {
    let num = 0
    for(let j = 1; j <= count.length - 1; j++) {
      if (count[j] === undefined) continue
      const as = A[i] !== j ? count[j] : count[j] - 1
      num += as * ( as - 1 ) / 2
    }
    console.log(num)
  }

}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [typescript]
import * as fs from 'fs';

namespace AtCoder.abc159 {

    class ProgramD {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 1 1 2 1 2
         * out
         * 2
         * 2
         * 3
         * 2
         * 3
         */
        main(): void {

            const n: number = parseInt(this.args[0], 10);
            const a: number[] = this.args[1].split(' ').map(Number);

            for (let i = 0; i < n; i++) {

                // const wk: number[] = [];
                // for (let j = 0; j < n; j++) {
                //     if (j !== i) {
                //         wk.push(a[j]);
                //     }
                // }

                let cnt: number = 0;
                for (let i2: number = 0; i2 < n ; i2++) {
                    if (i === i2) continue;
                    for (let j2: number = i2; j2 < n ; j2++) {
                        if (i === j2) continue;
                        if (j2 === i2) continue;
                        if (a[i2] === a[j2]) {
                            cnt++;
                        }
                    }
                }

                console.log(cnt);
            }
        }
    }

    const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
    const prg = new ProgramD(args);
    prg.main();
}
//  [typescript]
const stdin: string[] = [];

function main() {
    const As = stdin[1].split(" ").map(_ => parseInt(_));

    const m: {[index: string]: number} = {};
    As.forEach(A => {
        const a = `${A}`;
        m[a] = m[a] || 0;
        m[a] += 1;
    });
    const keys = Object.keys(m);
    
    const c: {[index: string]: number} = {};
    const d: {[index: string]: number} = {};
    keys.forEach(i => {
        c[i] = combi(m[i]);
        d[i] = combi(m[i] - 1);
    })
    
    As.forEach(A => {
        const a = `${A}`;
        const N = m[a] - 1;

        let t = 0;
        keys.filter(_ => a !== _).forEach(_ => t += c[_]);
        t += d[a];

        console.log(t);
    });
}

function fact(n: number) {
    let number = 1;
    for (let i = 1; i <= n; i ++) {
      number *= i;
    }
    return number;
}

function combi(n: number) {
    if (n < 2) {
        return 0;
    }
    return fact(n) / ( fact(2) * fact(n - 2) )
}

require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
}).on("line", _ => {
    stdin.push(_);
}).on("close", () => main());
//  [python]
n = int(input())
li = list(map(int, input().split()))
li = [[li[i], i] for i in range(n)]
li.sort()
count = 0
for i in range(n):
    if count > 2:
        print("NO")
        break
    if li[i][1] != i:
        count+=1
else:
    if count % 2 == 0: 
        print("YES")
    else:
        print("NO")
//  [python]
n = int(input())
p = list(map(int,input().split()))
pp = sorted(p)
def f(n,p,pp):
    flag =0
    for i in range(n):
        if p[i] != pp[i]:
            if flag == 2:
                return("NO")           
            else:
                flag += 1
    return("YES")
print(f(n,p,pp))
//  [python]
N = int(input())

p = list(map(int,input().split()))
plst = sorted(p)
count = 0
for i in range(N):
	if p[i] != plst[i]:
		count += 1

print("YES" if count <= 2 else "NO")
//  [python]
N = int(input())
p = list(map(int,input().split()))

if p == sorted(p):
    print('YES')
else:
    ret = 'NO'
    # 全通りの組み合わせをみて、昇順かどうか調べる
    for i in range(N-1):
        for j in range(i+1, N):

            # p[i]とp[j]より小さければ抜ける
            if p[i] < p[j]:
                continue
            else:
                k = p.copy()
                k[i], k[j] = k[j], k[i]

            is_sorted = True
            for l in range(N-1):
                if k[l+1] < k[l]:
                    is_sorted = False
                    break

            if is_sorted:
                ret = 'YES'
                break
        if is_sorted:
            break

    print(ret)
//  [python]
N = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(N):
  if p[i] != i+1:
    ans += 1

if ans <= 2:
  print("YES")
else:
  prin("NO")
//  [python]
n = int(input())
p = list(map(int, input().split()))
cnt = 0

for i in range(0, n-1):
    x = abs(p[i]-p[i+1])
    if x != 1:
        cnt += 1

if cnt < 3:
    print("YES")
else:
    print("NO")
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String args[]) throws Exception{
        BufferedReader stdR = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(stdR.readLine());
        int[] p = new int[N];
        String[] s = stdR.readLine().split(" ");
        for(int i = 0 ; i < N ; i++) {
            p[i] = Integer.parseInt(s[i]);
        }
        if(isOrder(p)) {
            System.out.println("YES");
        }else {
            boolean isok = false;
            for(int i = 0 ; i < N ; i++) {
                for(int j = i + 1 ; j < N ; j++) {
                    int tmp = p[i];
                    p[i] = p[j];
                    p[j] = tmp;
                    isok = isOrder(p);
                    if(isok) {
                        System.out.println("YES");
                        break;
                    }else {
                        p[j] = p[i];
                        p[i] = tmp;
                    }
                }
                if(isok)break;
            }   
            if(!isok)System.out.println("NO");
        }
        
    }
    
    public static boolean isOrder(int[] a) {
        int res = a[0];
        for(int i = 1 ; i < a.length ; i++) {
            if(res <= a[i]) {
                res = a[i];
            }else {
                return false;
            }
        }
        return true;
    }
}
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		int numberOfInput = input.nextInt();
		
		int[] array = new int[numberOfInput];
		
			for(int i=0;i<numberOfInput;i++) {
				
				array[i]=input.nextInt();
				
			}
			        
			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }
	      
		input.close();

	}

}
//  [java]
import java.util.Scanner;

public class Oor1Swap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		int numberOfInput = input.nextInt();
		
		int[] array = new int[numberOfInput];
		
			for(int i=0;i<numberOfInput;i++) {
				
				array[i]=input.nextInt();
				
			}
			        
			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }
	      
		input.close();

	}

}
//  [java]
import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		int numberOfInput = input.nextInt();
		
		int[] array = new int[numberOfInput];
		
			for(int i=0;i<numberOfInput;i++) {
				
				array[i]=input.nextInt();
        
			}
			        
			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }
	        
			}
		
		input.close();

	}

}
//  [cpp]
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, const char * argv[])
{
    int N;
    cin >> N;
    
    vector<int> P0;
    vector<int> P1;
    for (int i = 0; i < N; i++) {
        int tmp;
        cin >> tmp;
        P0.push_back(tmp);
        P1.push_back(tmp);
    }
    
    sort(P0.begin(), P0.end());
    
    int count = 0;
    for (int i = 0; i < N; i++) {
        if (P0[i] != P1[i]) {
            count++;
        }
        if (count >= 3) {
            break;
        }
    }
    
    if (count >= 3) {
        cout << "NO" << endl;
    }else {
     cout << "YES" << endl;
    }
}
//  [cpp]
#include<stdio.h>
#include<iostream>
#include <algorithm>

int main(){
    int n;
    scanf("%d",&n);
    int q[n];
    for(int i=0;i<n;i++){
        scanf("%d",&q[i]);
    }

    int a[n];

    int num=0;
    for(int i=0;i<n-1;i++){
        if(q[i]>q[i+1]){
            if(num==0){
            a[num]=i;
            }else{
            a[num]=i+1;
            }
            num++; 
        }
    }

    int tmp;
    if(num==2){
    tmp=q[a[0]];
    q[a[0]]=q[a[1]];
    q[a[1]]=tmp;  
    }

    

    bool flag=false;
     for(int i=0;i<n-1;i++){
         //printf("%d\n",flag);
         if(q[i]>q[i+1]){
             flag=true;
         }
     }

    if(flag){
        printf("%s\n","NO");

    }else{
        printf("%s\n","YES");
    }

    return 0;
}
//  [cpp]
#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
void aswap(int *a,int n);
int main()
{
	int n,a[50],i,i1=-1,i2=-1;
	bool s=false;
	cin>>n;
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(i=0;i<n-1;i++)
		if(a[i]!=i+1&&i1==-1)
		{
			i1=i;
			continue;	
		}
		else if(a[i]!=i+1&&i2==-1)
		{
			i2=i;
			swap(a[i1],a[i2]);
			i=-1;
			continue;
		}
		else if(a[i]!=i+1)
		{
			break;
		}
		else if(i==n-2) s=true;
	if(s) cout<<"YES";
	else cout<<"NO";
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define lower(s) transform(s.begin(), s.end(), s.begin(), ::tolower)
using namespace std;
using ll = long long;
int INF = 1001001001;

int main()
{
  int n;
  cin >> n;
  vector<int> p(n);
  vector<int> sp(n);
  rep(i, n) {
    int v;
    cin >> v;
    p[i] = sp[i] = v;
  }
  sort(sp.begin(), sp.end());
  int cnt = 0;
  rep(i, n)
  {
    if (p[i] != sp[i])
      cnt++;
    if (cnt >= 3)
    {
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;
  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;

int main() {
  int n;
  cin >> n;
  vector<int> vec(n);
  rep(i, n) {
    cin >> vec.at(i);
  }
  auto vec2 = vec;
  sort(vec2.begin(), vec2.end());
  string ans = "No";
  if (vec == vec2) ans = "Yes";
  else {
    for(int i = 0; i < n-1; i++) {
      for(int j = i + 1; j < n; j++) {
        swap(vec.at(i), vec.at(j));
        if (vec == vec2) ans = "Yes";
        else swap(vec.at(i), vec.at(j));
      }
    }
  }
  cout << ans << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main() {
  long N, x = 0, a = 0, b = 0, flag = 0;
  string ans = "Yes";
  cin >> N;
  
  for (int i = 1; i <= N; i++) {
    cin >> x;
    if (i != x && flag == 2) break;
    if (i != x && flag == 1) {
      if (x == a && i == b) ans = "Yes";
      flag = 2;
    }
        if (i != x && flag == 0) {
      a = i;
      b = x;
      flag = 1;
      ans = "No";
    }
  }
  
  cout << ans << endl;
}
//  [c]
#include <stdio.h>


int main(void){
    int N, i,a,b,c,d,j;
    int p[50], y=0, n=0;

    scanf("%d",&N);
    for( i=0; i<N;i++)
    scanf("%d",&p[i]);

    b=0;
    for(i=0; i<N-1;i++){
         if(p[i]>p[i+1] && b ==0 ){
            a=p[i];
            b=1;
            j=i;
         }
         else if( p[i]>p[i+1] && b==1){
             c=p[i+1];    
             p[i+1]=a;
             p[j]=c;
             b = 2;
         }
    }

    for(i=0; i < N-1;i++){
        if(p[i]>p[i+1])
            n=1;        
    }

    if ( N == 2)
        n = 0;

    if ( N == 3){
        for (i = 0; i<N;i++)
            if ( p[i]<p[i+1])
                n = 0;
    }

    if (n==1)
        printf("NO\n");
        else
        {
            printf("YES\n");
        }
        
//for (i=0;i<N;i++)
 //   printf("%d ", p[i]);
    


}
//  [c]
#include<stdio.h>
int main(void)
{
	int N;
	int count=0;
	scanf("%d", &N);
	int ary[N+1];
	for(int i=1;i<=N;i++){
		scanf("%d", &ary[i]);
		if(ary[i]==i){
			count=count+0;
			}
		else{count++;}
		
			
	}
	if(count==0 || count==2 ||count==1)printf("YES");
	else printf("NO");
	return 0;
	
}
//  [c]
#include<stdio.h>
#include<stdlib.h>

int main(void){
    int N;
    int i, j, k, l, m;
    int A;
    scanf("%d",&N);
    int p[N];
    for(i=0;i<N;i++){
        scanf("%d",&p[i]);
    }
// irekae
    for(j=0;j<N-1;j++){
        if(p[j+1]-p[j] < 1){
            A = p[j];
            p[j] = j+1;
            break;
        }
    }
    for(l=0;l<N-1;l++){
         if(p[l+1]-p[l] < 1){
            p[l+1] = A;
        }
    }
//    for(m=0;m<N;m++){
//        printf("a%d\n",p[m]);
//    }
//hantei
    for(k=0;k<N-1;k++){
        if(p[k+1]-p[k] != 1){
            printf("NO\n");
            exit(0);
        }
    }
    printf("YES\n");
    return 0;
}
//  [c]
#include<stdio.h>
#define SIZE 10000
int main()
{
    int i,n,a[SIZE],swp=0,tmp;
    scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
    }
    for(i=0;i<n;i++)
    {
        if(a[i]<a[i+1])
        {
            tmp = a[i];
            a[i] = a[i+1];
            a[i+1] = tmp;
            swp += 1;
        }
    }
    if(swp<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}
//  [c]
#include<stdio.h>
#define SIZE 100000
int main()
{
    int i,n,a[SIZE],swp=0,tmp;
    scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
    }
    for(i=0;i<n;i++)
    {
        if(a[i]<a[i+1])
        {
            tmp = a[i];
            a[i] = a[i+1];
            a[i+1] = tmp;
            swp += 1;
        }
    }
    if(swp<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}
//  [c]
#include<stdio.h>
#define SIZE 100000
int main()
{
    int i,n,a[SIZE], a1[SIZE],count=0;
    scanf("%d", &n);
    for(i=1;i<=n;i++)
    {
        a[i]=i;
    }
    for(i=1;i<=n;i++)
    {
        scanf("%d", &a1[i]);
        if(a1[i]!=a[i])
        {
            count++;
        }
    }
    if(count<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}
//  [javascript]
function Main(input) {
	inputs = input.split("\n");
	input = inputs[1].split(" ").map(Number);
	ans = true;
	culc = 0;
	temp = 0;
	
	for(var i = 0; i < input.length - 1; i++){
		if(input[i + 1] < input[i]){
			if(culc == 0){
				temp = input[i];
				number = i;
				culc++;
			}else{
				input[number] = input[i + 1];
				input[i + 1] = temp;
			}
		}
	}
	
	for(var i = 0; i < input.length - 1; i++){
		if(!(input[i] < input[i + 1])){
			ans = false;
		}
	}
	
	if(ans){
		console.log("YES");
	}else{
		console.log("NO");
	}

}Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(c){var b=c.split("\n");c=parseInt(b[0]);var d=[];b[1]=b[1].split(" ");for(var a=0;a<c;++a)d.push(parseInt(b[1][a],10));for(a=b=0;a<c;++a)d[a]!=a+1&&(b+=1);console.log(2>=b?"YES":"NO")}main(require("fs").readFileSync("/dev/stdin","utf8"));
//  [javascript]
'use strict';(function(input){

  input=input.trim().split(/\s+/).map(x=>x-0);
  
  const N = input[0];
  var counter = 0;
  for(let i=1;i<=N;i++){
    if(i!==input[i]){
      counter++;
    }
  }
  if(counter<=2){
    console.log('YES');
  }else{
    console.log('NO');
  }
})(require('fs').readFileSync('/dev/stdin','utf8'));
//  [javascript]
const main = input => {
  const inputs = input.trim().split('\n')

  const N = parseInt(inputs[0])
  const sequence = inputs[1].split(' ').map(x => parseInt(x))

  const sortedSample = sequence.slice().sort((a, b) => a - b)

  let diff = 0
  for (let i = 0; i < N; i++) {
    console.log(sequence[i], sortedSample[i]);
    if (sequence[i] !== sortedSample[i]) {
      diff++
    }
  }

  diff === 2 || diff === 0 ? console.log('YES') : console.log('NO')

}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [javascript]
const main = input => {
  const inputs = input.trim().split('\n')

  const N = parseInt(inputs[0])
  const sequence = inputs[1].split(' ')

  const sortedSample = sequence.slice().sort()

  let diff = 0
  for (let i = 0; i < N; i++) {
    if (sequence[i] !== sortedSample[i]) {
      diff++
    }
  }

  diff === 2 || diff === 0 ? console.log('YES') : console.log('NO')

}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [javascript]
"use strict";
function main(input) {
    const line = input.split("\n");
    const N = parseInt(line[0]);
    const p = line[1].split(" ").map(Number);
    let cnt = 0;
    for (let i = 0; i < N; i++) if (p[i] !== i + 1) cnt++;
    if (cnt <= 2) console.log("Yes");
    else console.log("No");
    return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import "fmt"

func main() {
	var N int
	fmt.Scanf("%d", &N)
	P := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &P[i])
	}
	mismatch := 0
	for i := 0; i < N; i++ {
		if P[i] != i+1 {
			mismatch++
		}
	}
	if mismatch == 0 || mismatch == 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

const (
	defaultBufferSize = 1024
	maxBufferSize     = 1e6
	Mod               = 1e9 + 7
)

var sc = bufio.NewScanner(os.Stdin)

// sc.Buffer(make([]byte, defaultBufferSize), maxBufferSize)

func readInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

func readString() string {
	sc.Scan()
	return sc.Text()
}

func readInt64() int64 {
	sc.Scan()
	i, err := strconv.ParseInt(sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return int64(i)
}

func readfloat64() float64 {
	sc.Scan()
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}

func abs(a int) int {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func ModComb(n, k int) int {
	if k == 0 {
		return 1
	}
	x, y := n, k
	for i := 1; i < k; i++ {
		x = x * (n - i) % Mod
		y = y * (k - i) % Mod
	}
	inv := ModInv(y)
	return x * inv % Mod
}

func ModFact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % Mod
	}
	return fact
}

func ModInv(x int) int {
	return ModPow(x, Mod-2)
}

func ModPow(a, n int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % Mod
		}
		a = a * a % Mod
		n /= 2
	}
	return res
}

func pow(a, n int) int {
	if n == 0 {
		return 1
	}

	ans := 0
	if n%2 == 0 {
		ans = pow(a*a, n/2)
	} else {
		ans = a * pow(a*a, (n-1)/2)
	}
	return ans
}

func intSliceReverse(slice []int) []int {
	for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
		slice[i], slice[j] = slice[j], slice[i]
	}
	return slice
}

func stringReverse(str string) string {
	runes := []rune(str)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func primeFactorization(x int) map[int]int {
	result := make(map[int]int, 0)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			result[i]++
			x /= i
		}
	}
	if x != 1 {
		result[x]++
	}
	return result
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	for i := 2; i*i <= x; i++ {
		if i == x {
			continue
		}
		if x%i == 0 {
			return false
		}
	}
	return true
}

func main() {
	sc.Split(bufio.ScanWords)
	n := readInt()
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt()
	}

	pasc := make([]int, n)
	copy(pasc, p)
	sort.Ints(pasc)

	count := 0
	for i, _ := range p {
		if p[i] != pasc[i] {
			count++
		}
	}
	if count <= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanLine() []int {
	var s []int
	scanner.Scan()
	for _, v := range strings.Split(scanner.Text(), " ") {
		i, _ := strconv.Atoi(v)
		s = append(s, i)
	}
	return s
}
func main() {
	var n int
	fmt.Scan(&n)
	p := scanLine()

	var SameWithIndex int
	for i, v := range p {
		if i+1 == v {
			SameWithIndex++
		}
	}
	if n-SameWithIndex <= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}
//  [go]
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
const ll MOD=(ll)1e9+7;
const ll INF=(ll)1e18+10;
const double PI=acos(-1);

template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
int dy[]={-1,1,0,0};
int dx[]={0,0,-1,1};

bool check(const vector<int> &a){
    int maxi=a[0];
    for (int i = 1; i < a.size(); ++i) {
        if(a[i]<maxi) return false;
        maxi = a[i];
    }
    return true;
}

void solve(int cn) {
    int N; cin>>N;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {
        cin>>a[i];
    }

    if(check(a)){
        cout<<"YES"<<endl;
        return;
    }

    for (int i = 0; i < N; ++i) {
        for (int j = i+1; j < N; ++j) {
            swap(a[i],a[j]);
            if(check(a)){
                cout<<"YES"<<endl;
                return;
            }
            swap(a[i],a[j]);
        }
    }
    cout<<"NO"<<endl;

}


#define SINGLE
int main() {
#ifdef SINGLE
    solve(1);
#else
    int N;
    cin>>N;
    for(int i=0;i<N;++i){
        solve(i);
    }
#endif
    return 0;
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	before := 0
	count := 0
	for i := 0; i < n; i++ {
		var v int
		fmt.Scanf("%d", &v)
		if v - before != 1 {
			count++
		}
		before++
	}
	fmt.Println(count)
	if count == 2 || count == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	before := 0
	count := 0
	for i := 0; i < n; i++ {
		var v int
		fmt.Scanf("%d", &v)
		if v - before != 1 {
			count++
			i++
		}
		before++
	}
	if count == 2 || count == 0  {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}
//  [ruby]
n = gets.chomp.to_i
p = gets.chomp.split(' ').map(&:to_i)
diff = 0
(1..n).each.with_index do |num, i|
  diff += 1 if (num != p[i])
end

if (diff == 0 || diff == 2)
  puts 'YES'
else
  puts 'NO'
end
//  [ruby]
n = gets.to_i
p = gets.chomp.split.map(&:to_i)
x = p.sort

sum = 0
p.zip(x).each do |i,y|
  if i == y
    sum += 1
  end
end

if sum >= n-2
  puts "YES"
else
  puts "NO"
end
//  [ruby]
N=gets.to_i
A=gets.split.map(&:to_i)

cnt=0
N.times do |i|
  if A[i] != i + 1
    cnt+=1
  end
end

if cnt == 2 || cnt == 0
  puts "YES"
else
  puts "NO"
end
//  [ruby]
n,*a=`dd`.split.map(&:to_i)
b=a.sort
c=0
n.times do |i|
  c+=1 if a[i]!=b[i]
  if c>1
    puts 'NO'
    exit
  end
end
puts 'YES'
//  [ruby]
n=gets.to_i
s=gets.chomp
a=s.sort
sum=0
for i in 0..n-1
  sum+=1 if s[i]!=a[i]
end
puts sum<=2? :YES: :NO
//  [ruby]
N = gets.to_i
P = gets.split.map(&:to_i)
s = P.sort

diff = 0
(0...N).each do |i|
  if P[i] != s[i]
    diff += 1
  end
end

if diff <= 2
  print "Yes\n"
else
  print "No\n"
end
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

fn main() {
    let n : usize = read();
    let v :Vec<usize> = read_vec();
    let mut c = 0;
    for i in 0..n {
        if v[i] != i+1 {
            c += 1;
        }
    }
    if c > 2 || c == 1 {
        println!("NO");
    }
    else {
        println!("YES");
    }
}
//  [rust]
use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let n = match buf.trim().parse::<i32>(){
		Ok(n) => n,
		_ => panic!(""),
	};
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v = Vec::new();
	for i in iter {
		match i.parse::<i32>() {
			Ok(j) => v.push(j),
			_ => panic!(""),
		}
	}
	let mut cnt = 0;
	for i in 0..n {
		if v[i as usize] != i + 1 {
			cnt += 1;
		}
		if cnt > 2 {
			break;
		}
	}
	if cnt > 2 {
		println!("NO");
	}else{
		println!("YES");
	}
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main(){

    input!{
        n: usize,
        p: [usize;n],
    }

    // let mut flag: bool = true;
    // let mut p_tmp:Vec<usize> = Vec::new();

    // for &value in &p{
    //     p_tmp.push(value);
    // }
    
    // for i in 0..n-1{
    //     for j in i..n{
    //         p_tmp.swap(i,j);
    //         flag = true;
    //         for k in 0..n-1{
    //             if p_tmp[k+1] < p_tmp[k]{
    //                 flag = false;  
    //                 break;
    //             }
    //         }   
    //         if flag == true {
    //             println!("YES");
    //             return;
    //         }
    //         p_tmp.swap(j,i);
    //     }
    // }

    // if flag == false{
    //     println!("NO");
    // }

    let mut cnt = 0;
    for i in 0..n{
        if p[i]!=i+1 {
            cnt+=1;
        }
    }

    if cnt > 2 {
        println!("NO");
    } else {
        println!("YES");
    }

}
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}


fn f(s: &Vec<i32>) -> bool{

    


    return true;
}

use std::iter::Iterator;
use std::cmp;


fn main() {
    input! {
        n : usize,
        p : [usize;n]
    }

    let mut cnt = 0;

    for (i ,val) in p.iter().enumerate() {
        if (i + 1) != *val {
            cnt = cnt + 1;
        }
    }

    if cnt == 2 {
        println!("YES");
    } else{
        println!("NO")
    }

}
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}


fn f(s: &Vec<i32>) -> bool{

    


    return true;
}

use std::iter::Iterator;
use std::cmp;


fn main() {
    input! {
        n : usize,
        p : [usize;n]
    }

    let mut cnt = 0;

    for (i ,val) in p.iter().enumerate() {
        if (i + 1) != *val {
            cnt = cnt + 1;
        }
    }

    if cnt == 2 {
        println!("Yes");
    } else{
        println!("No")
    }

}
//  [rust]
use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let n = match buf.trim().parse::<i32>(){
		Ok(n) => n,
		_ => panic!(""),
	};
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v = Vec::new();
	for i in iter {
		match i.parse::<i32>() {
			Ok(j) => v.push(j),
			_ => panic!(""),
		}
	}
	let mut cnt = 0;
	for i in 1..(n+1) {
		if v[i as usize] != i {
			cnt += 1;
		}
		if cnt > 2 {
			break;
		}
	}
	if cnt > 2 {
		println!("NO");
	}else{
		println!("YES");
	}
}
//  [swift]
let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i] != ppw[i]{
    count+=1
  }
}
if count==2 || count==0{
  print("YES")
}else{
  print("NO")
}
//  [swift]
readLine();let i=readLine()!.characters.split(" ").enumerate().reduce(0){$0+($1.0+1==Int(String($1.1))! ?0:1)};print(i==0||i==2 ?"YES":"NO")
//  [swift]
let a=Int(readLine()!)!
let arr=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}

var i = 0
var diff = 0

for i in 0..<a {
  if( arr[i] != i + 1 ) {
    diff += 1
  }

}

if ( diff <= 2 ) {
  print( "YES" )
} else {
  print( "NO" )
}
//  [swift]
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

let reader=readInts()
let n=reader[0]
var p=readInts()
var sorted=p
sorted.sort { $0 < $1 }
var diff=0

for i in 0..<n{
  if p[i] != sorted[i]{diff+=1}
}

if diff==2||diff==0{print("Yes")}else{print("No")}
//  [swift]
let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i] != ppw[i]{
    count+=1
  }
}
if count==2{
  print("YES")
}else{
  print("NO")
}
//  [swift]
let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i]!=ppw[i]{
    count+=1
  }
}
if count==2{
  print("YES")
}else{
  print("NO")
}
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')
const data = stdin
  .trim()
  .split('\n')[1]
  .split(' ')
  .map(n => Number.parseInt(n))

const x = data.map((n, i) => (n === i + 1 ? 0 : 1)).reduce((prev, cur) => prev + cur, 0)

console.log(x === 0 || x === 2 ? 'YES' : 'NO')
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const ps = input[1].split(" ").map(a => Number(a));
  const indices = [];
  for(let i = 0; i < n; i++) {
    const p = ps[i];
    if (i+1 !== p) indices.push(i);
  }
  let result = "NO";
  if (indices.length === 0 || indices.length === 2) result = "YES";
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = tmp[0].split(" ").map(int => parseInt(int))[0];
    const p: number[] = tmp[1].split(" ").slice(0, n).map(int => parseInt(int));
    const pCopy: number[] = [].concat(p);
    pCopy.sort((a, b) => a - b);
    let count: number = 0;
    for (let i = 0; i < n; i++) {
      if (p[i] != pCopy[i]) {
        count++;
      }
    }
    return `${count == 0 || count == 2 ? "YES" : "NO"}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
import * as fs from 'fs';

namespace AtCoder.abc135 {

    export class Program {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 5 2 3 4 1
         * out
         * Yes
         */
        main(): void {
            let p: number [] = this.args[1].split(' ').map(x => parseInt(x, 10));
            const sorted: number[] = this.args[1].split(' ').map(x => parseInt(x, 10)).sort();

            let cnt: number = 0;
            for (let i = 0; i < p.length; i++) {
                if (p[i] !== sorted[i]) {
                    cnt++;
                }
                if (cnt > 2) {
                    console.log('NO');
                    return;
                }
            }
            console.log('YES');
        }
    }

}

const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const prg = new AtCoder.abc135.Program(args);
prg.main();
//  [typescript]
import * as fs from 'fs';

namespace AtCoder.abc135 {

    export class Program {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 5 2 3 4 1
         * out
         * Yes
         */
        main(): void {
            let p: number [] = this.args[1].split(' ').map(x => parseInt(x, 10));
            const sorted: number[] = this.args[1].split(' ').map(x => parseInt(x, 10)).sort();

            let cnt: number = 0;
            for (let i = 0; i < p.length; i++) {
                if (p[i] !== sorted[i]) {
                    cnt++;
                }
                if (cnt > 2) {
                    console.log('No');
                    return;
                }
            }
            console.log('Yes');
        }
    }

}

const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const prg = new AtCoder.abc135.Program(args);
prg.main();
//  [typescript]
const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let s=t.n(n)
  let c=0;
  for(let i=0;i<n;i++){
    if(s[i] != i+1) c++
  }
  t.o(c==2?'YES':'NO')
}
main()
//  [python]
N,x = map(int,input().split())
li = list(map(int,input().split()))

newLi = sorted(li)
ans = 0

for i in range(len(newLi)):
  if x - newLi[i] < 0:
    break
   
  if i == (len(newLi) - 1) and x != newLi[i]:
    break
  
  x -= newLi[i]
  ans += 1

print(ans)
//  [python]
N, x = map(int, input().split())
a = list(map(int, input().split()))

# 小さい数から配っていくと子供の人数を最大化できる
a = sorted(a)

leftCandy = x
childrenCnt = 0
for i in range(len(a)):
  leftCandy -= a[i]
  if leftCandy >= 0:
    childrenCnt += 1

if leftCandy > 0:
  childrenCnt -= 1

print(childrenCnt)
//  [python]
N, x = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
count = 0
for i in range(N):
    x = x - a[i]
    if x < 0:
        break
    count += 1  
if x > 0:
    count -= 1
print(count)
//  [python]
N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    break
    print(z+1)
else:
  print(n-1)
//  [python]
N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    print(z+1)
    break
else:
  print(N)
//  [python]
N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    print(z+1)
    break