jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
# ABC 166 E - This Message Will Self-Destruct in 5s
# https://atcoder.jp/contests/abc166/tasks/abc166_e

# TLE
# https://atcoder.jp/contests/abc166/submissions/12768938

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map(&:to_i)

class Person
  def initialize(index, height)
    @index = index
    @height = height
  end

  attr_reader :index, :height

  def index_minus_height
    @index_minus_height ||= index - height
  end

  def index_plus_height
    @index_plus_height ||= index + height
  end
end

people = a.map.with_index(1) { |height, i| Person.new(i, height) }

h_index_minus_height = Hash.new
h_index_plus_height = Hash.new

people.each do |person|
  h_index_minus_height[person.index_minus_height] ||= []
  h_index_plus_height[person.index_plus_height] ||= []

  h_index_minus_height[person.index_minus_height].push(person)
  h_index_plus_height[person.index_plus_height].push(person)
end

count = 0

h_index_minus_height.each do |index_minus_height, people_from_index_minus_height|
  people_from_index_plus_height = h_index_plus_height[index_minus_height]
  next if people_from_index_plus_height.nil?
  people_in_both_array = people_from_index_minus_height & people_from_index_plus_height
  count += people_from_index_minus_height.size * people_from_index_plus_height.size - people_in_both_array.size
end

puts count
//  [ruby]
require 'set'

N = STDIN.gets.to_i - 1
A = STDIN.gets.split(' ').map(&:to_i)

l = {}
r = {}

k = Set.new

0.upto(N) do |i|
  l[i + A[i]] ||= []
  l[i + A[i]] << i
  k.add(i + A[i])

  r[i - A[i]] ||= []
  r[i - A[i]] << i
  k.add(i - A[i])
end

c = 0

k.each do |i|
  if r[i] && l[i]
    c += r[i].count * l[i].count
  end
end

print c
//  [ruby]
# frozen_string_literal: true

n = gets.to_i
a = gets.split.map(&:to_i)

l = Hash.new {|h,k| h[k]=[]}
r = Hash.new {|h,k| h[k]=[]}

a.each_with_index do |e, i|
  l[e + i].push i
  r[i - e].push i
end
count = 0
l.each do |k, v|
  count += r[k].size * l[k].size if r[k]
end
puts count
//  [rust]
#![allow(unused_imports)]
use proconio::input;
use proconio::marker::*;
use proconio::fastout;

#[fastout]
fn main() {
    input! {
    n: usize,
    al: [usize; n]
    }
    let mut l = vec![0; n];
    let mut ans:usize = 0;
    for i in 0..n{
        let a = al[i];
        if a + i < n {
            l[i + a] += 1;
        }
        if i >= a {
            ans += l[i - a];
        }
    }
    println!("{}", ans);
}
//  [rust]
#[warn(unused_imports)]
use proconio::{
   fastout, input,
   marker::{Bytes, Chars, Isize1, Usize1}
};

#[fastout]
fn main() {
   input! {
      n: usize,
      a: [usize; n]
   }
   let mut dp = vec![0 as usize; n];
   let mut ans: usize = 0;
   for i in 1..=n {
      if a[i-1] <= i {
         ans += dp[i-a[i-1]];
      }
      if a[i-1] + i < n {
         dp[a[i-1]+i] += 1;
      }
   }
   println!("{}", ans);
}
//  [rust]
use proconio::input;
use std::collections::BTreeMap;
use superslice::*;

fn main() {
    input! {
        n: usize,
        a: [i64; n],
    };
    // j - i = a[i] + a[j] (i < j) が条件より i + a[i] = j - a[j] (i < j)
    let mut l = vec![0_i64; n];
    let mut r = vec![0_i64; n];
    for (i, &a_i) in a.iter().enumerate() {
        l[i] = i as i64 + a_i;
        r[i] = i as i64 - a_i;
    }
    // l[i] = r[j] (i < j) となる (i, j) の個数
    let mut ml: BTreeMap<i64, Vec<usize>> = BTreeMap::new();
    let mut mr: BTreeMap<i64, Vec<usize>> = BTreeMap::new();
    for (i, (&l_i, &r_i)) in l.iter().zip(r.iter()).enumerate() {
        ml.entry(l_i).and_modify(|e| e.push(i)).or_insert(vec![i]);
        mr.entry(r_i).and_modify(|e| e.push(i)).or_insert(vec![i]);
    }
    let ans = ml
        .iter()
        .map(|(x, li)| {
            li.iter()
                .map(|&i| {
                    mr.get(&x)
                        .map(|lj| lj.len() - lj.upper_bound(&i))
                        .unwrap_or(0)
                })
                .sum::<usize>()
        })
        .sum::<usize>();
    println!("{}", ans);
}
//  [rust]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(dead_code)]

use itertools::Itertools;
use proconio::input;
use proconio::marker::{Chars, Usize1};

#[allow(unused_macros)]
#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    //($arg:expr) => (println!("{:?}",$arg));
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
      }
}
#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::*;
use std::collections::*;
use std::ops::{Add, Div, Mul, Sub};

#[allow(dead_code)]
static INF_I64: i64 = 92233720368547758;
#[allow(dead_code)]
static INF_I32: i32 = 21474836;
#[allow(dead_code)]
static INF_USIZE: usize = 18446744073709551;
#[allow(dead_code)]
static M_O_D: usize = 1000000007;
#[allow(dead_code)]
static PAI: f64 = 3.1415926535897932;

trait IteratorExt: Iterator {
    fn toVec(self) -> Vec<Self::Item>;
}

impl<T: Iterator> IteratorExt for T {
    fn toVec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

trait CharExt {
    fn toNum(&self) -> usize;
    fn toAlphabetIndex(&self) -> usize;
    fn toNumIndex(&self) -> usize;
}
impl CharExt for char {
    fn toNum(&self) -> usize {
        return *self as usize;
    }
    fn toAlphabetIndex(&self) -> usize {
        return self.toNum() - 'a' as usize;
    }
    fn toNumIndex(&self) -> usize {
        return self.toNum() - '0' as usize;
    }
}

trait VectorExt {
    fn joinToString(&self, s: &str) -> String;
}
impl<T: ToString> VectorExt for Vec<T> {
    fn joinToString(&self, s: &str) -> String {
        return self
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(s);
    }
}

trait StringExt {
    fn get_reverse(&self) -> String;
}
impl StringExt for String {
    fn get_reverse(&self) -> String {
        self.chars().rev().collect::<String>()
    }
}

trait UsizeExt {
    fn pow(&self, n: usize) -> usize;
}
impl UsizeExt for usize {
    fn pow(&self, n: usize) -> usize {
        return ((*self as u64).pow(n as u32)) as usize;
    }
}

fn main() {
    input! {
       N: usize,
       A:[i64;N],
    }
    mydbg!(A);

    let mut a = vec![(0, 0); N];
    let mut b = vec![(0, 0); N];
    for i in 0..N {
        a[i] = ((i + 1) as i64 + A[i], i);
        b[i] = ((i + 1) as i64 - A[i], i);
    }
    //let mut ans = HashSet::new();
    let mut ans = 0;
    mydbg!(a);
    mydbg!(b);
    let mut ah = HashMap::new();
    let mut bh = HashMap::new();
    for i in 0..N {
        let mut hp = ah.entry(a[i].0).or_insert(vec![]);
        hp.push(a[i].1);
        let mut hp = bh.entry(b[i].0).or_insert(vec![]);
        hp.push(b[i].1);
    }
    for (key, value) in &ah {
        match bh.get(&key) {
            Some(x) => {
                ans += value.len() * x.len();
            }
            None => {}
        }
    }

    //echo!(ans);
    mydbg!(ans);
    echo!(ans);
}
//  [swift]
let n = Int(readLine()!)!
let a = readLine()!.split(separator: " ").map { Int($0)! }

var iDict = [Int: Int]()
var jDict = [Int: Int]()

a.enumerated().forEach { (i, v) in
  iDict[i+v] = iDict[i+v] ?? 0
  iDict[i+v]? += 1
  jDict[i-v] = jDict[i-v] ?? 0
  jDict[i-v]? += 1
}

var c = 0
iDict.forEach { (v, iIndicesNum) in
  let jIndicesNum = jDict[v] ?? 0
  c += iIndicesNum * jIndicesNum
}

print(c)
//  [swift]
let n = Int(readLine()!)!
let a = readLine()!.split(separator: " ").map { Int($0)! }

var iDict = [Int: Int]()
var jDict = [Int: Int]()

a.enumerated().forEach { (i, v) in
  iDict[i+v] = iDict[i+v] ?? 0
  iDict[i+v]? += 1
  jDict[i-v] = jDict[i-v] ?? 0
  jDict[i-v]? += 1
}

var c = 0
iDict.forEach { (v, iIndicesNum) in
  if let jIndicesNum = jDict[v] {
    c += iIndicesNum * jIndicesNum
  }
}

print(c)
//  [swift]
import Foundation

private func readString() -> String {
    readLine()!
}

private func readStringArray() -> [String] {
    readString().components(separatedBy: " ")
}

private func readInt() -> Int {
    Int(readString())!
}

private func readIntArray() -> [Int] {
    readStringArray().map { Int($0)! }
}

private func readStringTupple() -> (String, String) {
    let array = readStringArray()
    return (array[0], array[1])
}

private func readStringTupple() -> (String, String, String) {
    let array = readStringArray()
    return (array[0], array[1], array[2])
}

private func readIntTupple() -> (Int, Int) {
    let array = readIntArray()
    return (array[0], array[1])
}

private func readIntTupple() -> (Int, Int, Int) {
    let array = readIntArray()
    return (array[0], array[1], array[2])
}

private func pow(_ x: Int, _ y: Int) -> Int {
    Int(pow(Double(x), Double(y)))
}

/*＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿
 〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓
 ￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣*/

let n = readInt()
let a = [-1] + readIntArray()
var x = [Int](repeating: 0, count: n + 1)
var y = [Int](repeating: 0, count: n + 1)
for i in 1 ..< n + 1 {
    if a[i] + i < n + 1 {
        x[a[i] + i] += 1
    }
    if i - a[i] >= 1 {
        y[i - a[i]] += 1
    }
}
print((1 ..< n + 1).map { x[$0] * y[$0] }.reduce(0) { $0 + $1 })

/*＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿
〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓
￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣￣*/
//  [swift]
_ = readLine()
let inp = readLine()!.split(separator: " ").map { Int($0)! }

let As = inp.enumerated().map { i, n -> (Int, Int, Int, Int) in
    return (i+1, n, i+n, i-n)
}

let dic2 = Dictionary(grouping: As, by: \.2)
let dic3 = Dictionary(grouping: As, by: \.3)


var r = 0
for i in As {
    let r2 = (dic2[i.3] ?? []).count
    let r3 = (dic3[i.2] ?? []).count
    r += r2 + r3
}

print(r/2)
//  [typescript]
class NormalInput {
  input: string[];
  pointer: number;
  constructor(raw: string) {
    this.input = raw.split(/ |\n/);
    this.pointer = 0;
  }
  read<T>(parser: (v: string) => T): () => T {
    return () => {
      const ret = parser(this.input[this.pointer]);
      this.pointer++;
      return ret;
    };
  }
  int = this.read((str) => parseInt(str, 10));
  ints = (length: number): number[] => {
    let ret: number[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.int());
    }
    return ret;
  };
  str = (): string => {
    const ret = this.input[this.pointer];
    this.pointer++;
    return ret;
  };
  strs = (length: number): string[] => {
    let ret: string[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.str());
    }
    return ret;
  };
  bint = (): bigint => {
    const ret = BigInt(this.input[this.pointer]);
    this.pointer++;
    return ret;
  };
  bints = (length: number): bigint[] => {
    let ret: bigint[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.bint());
    }
    return ret;
  };
}
function rep(a: number, b: number) {
  let arr = [];
  for (let i = a; i < b; i++) arr.push(i);
  return arr;
}

function Main({ int, str, strs, ints, bint, bints }: NormalInput) {
  const N = int();
  const A = bints(N);
  let minus: Map<bigint, number> = new Map();
  let plus: Map<bigint, number> = new Map();
  for (let i = 0; i < N; i++) {
    const m = A[i] - BigInt(i);
    const p = A[i] + BigInt(i);
    minus.set(m, (minus.has(m) ? minus.get(m)as number : 0) + 1);
    plus.set(p, (plus.has(p) ? plus.get(p)as number : 0) + 1);
  }
  let ans = 0n;
  minus.forEach((m, i) => {
    if (plus.has(-i)) {
      const p = plus.get(-i) as number;
      ans += BigInt(m * p);
    }
  });
  console.log(ans + "");
}

//DO NOT EDIT
Main(new NormalInput(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [python]
import sys
input=sys.stdin.readline

fact = [1]
for i in range(1,8+1):
  fact.append(fact[i-1]*i)


def seq_to_index(seq):
  #print?g()
  seq_len=len(seq)
  unused_val=[i+1 for i in range(seq_len)]
  index=0
  for i in range(seq_len):
  #for i in reversed(range(0,seq_len)):
    ##print?g(i)
    #先頭の数字*それまでに通過してきた組み合わせ
    coeff = seq[i]
    coeff_index_in_unused = unused_val.index(coeff)
    index+=coeff_index_in_unused*fact[seq_len-1-i]
    #使用済みの数は削除
    #print?g(coeff,
    #unused_val,
    #coeff_index_in_unused,
    #index,
    #fact[seq_len - 1 - i])

    unused_val.remove(coeff)

  #print?g()
  return index
    
n=input()

P = list(map(int, input().split()))
Q = list(map(int, input().split()))

pindex=seq_to_index(P)
qindex=seq_to_index(Q)

#print?g(pindex)
#print?g(qindex)

print(qindex-pindex if qindex>pindex else pindex-qindex)
//  [python]
import math

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

ans_P = 0
for i in range(N):
    P_sort = sorted(P)
    a = P_sort.index(P[0])
    n = math.factorial(N-1-i)*a
    ans_P += n
    del P[0]

ans_Q = 0
for i in range(N):
    Q_sort = sorted(Q)
    a = Q_sort.index(Q[0])
    n = math.factorial(N-1-i)*a
    ans_Q += n
    del Q[0]

print(abs(ans_Q - ans_P))
//  [python]
import math

N = int(input())
P = input().split()
Q = input().split()
P = list(map(int, P))
Q = list(map(int, Q))

a = 0

for i, p in enumerate(P, start=1):
  for j in range(1, p):
    if not j in P[:i-1]:
    	a += math.factorial(N-i)
    
b = 0

for i, q in enumerate(Q, start=1):
  for j in range(1, q):
    if not j in Q[:i-1]:
      b	+= math.factorial(N-i)

sum = a - b
if sum < 0:
  sum *= -1

print(sum)
//  [python]
import numpy as np
import itertools
from sys import stdin
lines = stdin.readlines()
 
N = int(lines[0])
P = list(map(str, lines[1].split()))
Q = list(map(str, lines[2].split()))

permu = []
for a in range(N):
  permu.append(str(a + 1))

#print(permu)

cnt_a = 1
for p in itertools.permutations(permu):
  cnt_a += 1
  p_act = np.array(p)
  p_test = np.array(P)
  if (p_test == p_act).all() == True:
    a = cnt_a

cnt_b = 1
for q in itertools.permutations(permu):
  cnt_b += 1
  q_act = np.array(q)
  q_test = np.array(Q)
  if (q_test == q_act).all() == True:
    b = cnt_b

print(abs(a - b))
//  [python]
import numpy as np

N = int(input())
P = [int(p) for p in input().split()]
Q = [int(q) for q in input().split()]

def factorial(n):
    ret = 1
    for i in range(1, n+1):
        ret *= i
    return ret

a = 0
used_l = []
for i in range(N):
    a += factorial(N-1-i)*(P[i]-1-np.sum(P[i]>np.array(used_l)))
    used_l.append(P[i])

b = 0
used_l = []
for i in range(N):
    b += factorial(N-1-i)*(Q[i]-1-np.sum(Q[i]>np.array(used_l)))
    used_l.append(Q[i])

print(abs(a-b))
//  [python]
# -*- coding:utf-8 -*-
import copy

def solve():
    N = int(input())
    Ps = tuple(map(int, input().split()))
    Qs = tuple(map(int, input().split()))

    available_list = [i for i in range(1, N+1)]

    permutations = []  # 順列
    def _dfs(rest_list, p):
        if len(rest_list) == 0:
            permutations.append(tuple(p))
            return

        for i in range(1, N+1):
            if i in rest_list:
                tmp_rest_list = copy.deepcopy(rest_list)
                tmp_rest_list.remove(i)
                tmp_p = copy.deepcopy(p)
                tmp_p.append(i)
                _dfs(tmp_rest_list, tmp_p)


    _dfs(available_list, [])

    permutations.sort()

    for i, p in enumerate(permutations):
        if p == Ps:
            a = i+1
        if p == Qs:
            b = i+1

    print(abs(a-b))


if __name__ == "__main__":
    solve()
//  [java]
import java.util.*;
import java.io.*;

public class Main {

	private static void solve(){
		//Implement solution here.
		int n = ni();
		int[] p = na(n);
		int[] q = na(n);
		System.out.println(Math.abs(count(n,p) - count(n,q)));
	}
	
	private static int count(int n, int[] a) {
		int[] factorial = {0,1,2,6,24,120,720,5040};
		int usedcnt = 0;
		boolean[] used = new boolean[n];
		int result = 1;
		for(int ai:a) {
			int cnt = 0;
			used[ai - 1] = true;
			usedcnt++;
			for(int i = 0; i < ai; i++)if(!used[i])cnt++;
			result += cnt * factorial[n - usedcnt];
		}
		return result;
	}

	//Switch input source (stdin/file)
	private static BufferedReader br;
	public static void main(String[] args){
		br = new BufferedReader(new InputStreamReader(System.in));
		String debugDataPath = System.getenv("DD_PATH");        
		if(debugDataPath != null){
			try{
				br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(debugDataPath))));
			}catch(Exception e){
				throw new RuntimeException(e);
			}
		}
		solve();
	}

	//Input read utility
	private static StringTokenizer tokenizer = null;
	public static String next() {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			try {
				tokenizer = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken();
	}
	//Get next single int
	private static int ni() {
		return Integer.parseInt(next());
	}
	//Get next single long
	private static long nl() {
		return Long.parseLong(next());
	}
	//Get next single double
	private static double nd() {
		return Double.parseDouble(next());
	}
	//Get next int array from one line
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}
	//Get next char array from one line
	private static char[] ns() {
		return next().toCharArray();
	}
	//Get next long array from one line
	private static long[] nal(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}
}
//  [java]
import java.util.*;
import java.io.*;

// This file is a "Hello, world!" in Java language by OpenJDK for wandbox.

class Main
{
    public static void main(String[] args)
    {
        new Main().run();
    }
    
    void run(){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        int[] P=new int[N];
        int[] Q=new int[N];
        int n1=0,n2=0;
        for(int i=0;i<N;++i)P[i]=sc.nextInt();
        for(int i=0;i<N;++i)Q[i]=sc.nextInt();
        for(int i=0;i<N;++i)n1=n1*10+P[i];
        for(int i=0;i<N;++i)n2=n2*10+Q[i];
        int ans=0;
        if(n1>n2){
            n1^=n2;
            n2^=n1;
            n1^=n2;
        }
        while(true){
            if(n1==n2)break;
            ++n1;
            while(!ok(n1,N))++n1;
            ++ans;
        }
        System.out.println(ans);
    }
    
    boolean ok(int v,int n){
        boolean[] f=new boolean[10];
        while(v>0){
            if(f[v%10])return false;
            f[v%10]=true;
            v/=10;
        }
        boolean ret=true;
        for(int i=1;i<=n;++i)ret&=f[i];
        return ret;
    }
}

// OpenJDK reference:
//   http://openjdk.java.net/

// Java language references:
//   http://docs.oracle.com/javase
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        main.solve();
    }

    public void solve() {
        Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int N = scan.nextInt();
        List<Integer> candidate = new ArrayList<>();
        for (int i = 1; i <= N; i++) {
            candidate.add(i);
        }
        scan.nextLine();
        String p = scan.nextLine();
        String q = scan.nextLine();
        List<List<Integer>> list = make(candidate);
        List<String> strings = new ArrayList();
        for (List<Integer> x : list) {
            strings.add(x.stream().map(i -> i.toString()).collect(Collectors.joining(" ")));
        }
        int len = strings.size();
        int l = 0;
        int r = 0;
        for (int i = 0; i < len; i++) {
            if (p.equals(strings.get(i))) {
                l = i;
            }
            if (q.equals(strings.get(i))) {
                r = i;
            }
        }
        System.out.println(Math.abs(l - r));
    }

    public static List<List<Integer>> make(List<Integer> candidate) {
        if (candidate.size() == 0) {
            List<List<Integer>> empty = new ArrayList<>();
            empty.add(new ArrayList<>());
            return empty;
        }

        return candidate.stream().flatMap(i -> {
            List<Integer> rest = new ArrayList<>(candidate);
            rest.remove(i);
            return make(rest).stream().map(list -> {
                list.add(0, i);
                return list;
            });
        }).collect(Collectors.toList());
    }
}
//  [java]
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {
        final Scanner sc = new Scanner(System.in);

        final int n = sc.nextInt();

        final int[] p = new int[n];
        for (int i = 0; i < n; i++) {
            p[i] = sc.nextInt();
        }

        final int[] q = new int[n];
        for (int i = 0; i < n; i++) {
            q[i] = sc.nextInt();
        }

        List<List<Integer>> list = new ArrayList<>();

        perm(IntStream.rangeClosed(1, n).boxed().collect(Collectors.toList()), new ArrayList<>(), list);

        List<Integer> lp = IntStream.of(p).boxed().collect(Collectors.toList());
        List<Integer> lq = IntStream.of(q).boxed().collect(Collectors.toList());

        int np = 0;
        int nq = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).toString().equals(lp.toString())) np = i + 1;
            if (list.get(i).toString().equals(lq.toString())) nq = i + 1;
        }

        System.out.println(Math.abs(np - nq));
    }

    private static void perm(List<Integer> candidate, List<Integer> perm, List<List<Integer>> perms) {
        if (candidate.size() == 0) {
            perms.add(perm);
        }
        for (int i = 0; i < candidate.size(); i++) {
            List<Integer> c = new ArrayList<>(candidate);
            List<Integer> p = new ArrayList<>(perm);
            p.add(c.get(i));
            c.remove(i);
            perm(c, p, perms);
        }
    }
}
//  [cpp]
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <string>
#include <map>
#define rep(i,N) for(int i=0; i<N;i++)
using namespace std;

int factorial(int a){
    int ans=1;
    rep(i,a){
        ans*=(i+1);
    }
    return ans;
};


int main(){
    int N;
    cin >>N;
    vector<int> P(N),Q(N),countP(N),countQ(N);
    int orderP=1;int orderQ=1;
    int n1,n2;
    rep(i,N){
        cin >> P[i];
    }
    rep(i,N){
        cin >> Q[i];
    }
    rep(i,N){
        countP[i]=1;
        countQ[i]=1;
    }
    rep(i,N){
        n1=0;
        n2=0;
        rep(j,P[i]-1){
            n1+=countP[j];
        }
        rep(j,Q[i]-1){
            n2+=countQ[j];
        }
        orderP+=n1*factorial(N-i-1);
        orderQ+=n2*factorial(N-i-1);
        countP[P[i]-1]=0;
        countQ[Q[i]-1]=0;
    }
    cout << abs(orderP-orderQ) << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int com(int x){
  int ans = 1;
  for(int i = 1; i <= x; i++){
    ans *= i;
  }
  return ans;
}

int main() {
  int N;
  cin >> N;
  vector<int> p(N), q(N), P(N), Q(N);
  for(int i = 0; i < N; i++){
    cin >> p.at(i);
    P.at(i) = p.at(i);
  }
  for(int i = 0; i < N; i++){
    cin >> q.at(i);
    Q.at(i) = q.at(i);
  }
  
  int ans = 0;
  //cout << "p q p q r" << endl;
  for(int i = 0; i < N; i++){
    int re = com(N - i - 1);
    int ansa = 0;
    //cout << P.at(i) << " " << Q.at(i) << " ";
    if(i == 0){
      ansa = (p.at(i) - q.at(i)) * re;
    }
    else{
      for(int j = 0; j < i; j++){
        if(P.at(i) > P.at(j)){
          p.at(i)--;
        }
        if(Q.at(i) > Q.at(j)){
          q.at(i)--;
        }
      }
      ansa = (p.at(i) - q.at(i)) * re;
    }
    //cout << p.at(i) << " " << q.at(i) << " ";
    ans += ansa;
    //cout << re << endl;
  }
  
  cout << abs(ans) << endl;
    
}
//  [cpp]
#include <iostream>
#include <fstream>
#include <math.h>
#include <string>

using namespace std;

int main(){

  int n, tmp_p, tmp_q;
  long long factorial, order_p=0, order_q=0;
  cin >> n;
  int p[n], q[n];
  for(int i=0; i<n; i++){ cin >> p[i];}
  for(int i=0; i<n; i++){ cin >> q[i];}

  for(int i=0; i<n; i++){
    //    cout << "i=" << i << endl;
    factorial = 1;
    for(int j=1; j<n-i; j++){
      factorial *= j;
    }
    tmp_p = 0; tmp_q = 0;
    for(int j=0; j<i; j++){
      if(p[j]<p[i]) tmp_p++;
      if(q[j]<q[i]) tmp_q++;
    }
    order_p += factorial * (p[i] - 1 - tmp_p);
    order_q += factorial * (q[i] - 1 - tmp_q);
    //cout << "tmp:" << (p[i] - 1 - tmp_p) << endl;
    //cout << "facto:" << factorial << endl;
    //cout << "order_p:" << order_p << endl;

  }
  //cout << order_p << " " << order_q << endl;
  cout << abs(order_p-order_q);

}
//  [cpp]
#include<iostream>
#include<algorithm>
using namespace std;
int rui(int a,int b){
	if(b==0)return 1;
	return a*rui(a,b-1);
}
int main(){
	int N,P=0,Q=0,pre,num=0,re,a=0,b=0;
	bool te[10],flag;
	cin>>N;
	for(int i=0;i<N;i++){
		cin>>re;
		P+=re;
		P*=10;
	}
	P/=10;
	for(int i=0;i<N;i++){
		cin>>re;
		Q+=re;
		Q*=10;
	}
	Q/=10;
	for(int i=rui(10,N-1);i<rui(10,N);i++){
		pre=i;
		flag=false;
		for(int j=0;j<10;j++)te[j]=false;
		for(int j=0;j<N;j++){
			if(te[pre%10]||pre%10>N||pre%10==0){flag=true;break;}
			te[pre%10]=true;
			pre/=10;
		}
		if(!flag)num++;
		if(i==P)a=num;
		if(i==Q)b=num;
		if(a!=0 && b!=0)break;
	}
	cout<<max(a-b,b-a);
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
int main()
  {
  int n;
  int x, y;
  cin >> n;
  int ar1[9];
  int ar2[9];
  for(int i=0;i<=n-1;i++)
  {
      scanf("%d",&ar1[i]);
  }
  for(int i=0;i<=n-1;i++)
  {
      scanf("%d",&ar2[i]);
  }
  int res=0;
  res=res+ar1[n-1];
  int mul=10;
  for(int i=n-2;i>=0;i--)
  {
      res=res+mul*ar1[i];
      mul=mul*10;
  }
  int res2=0;
  res2=res2+ar2[n-1];
  int mul2=10;
  for(int i=n-2;i>=0;i--)
  {
      res2=res2+mul2*ar2[i];
      mul2=mul2*10;
  }

  x=min(res,res2);
  y=max(res,res2);
  bool ar[n+1];
  int r;
  int cnt =0;
  bool flag;
  for(int i=x; i<=y;i++)
    {
    flag=true;
    memset(ar,0,sizeof(ar));
     r=i;
    while(r>0)
      {
      ar[r%10]=1;
      r=r/10;
      }
    for(int j=1;j<=n;j++){
      if(ar[j]==false)
        { flag= false;
          break;
         }
      }
    if(flag ==true)
      cnt++;

  }
 cout << cnt-1 << endl;
return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define itn int
#define mod 1000000007
#define INFi 2147483647
#define INFl 9223372036854775807LL
#define fi first
#define se second
#define be begin()
#define en end()
int abs(int a,int b){
    return max(a,b)-min(a,b);
}
signed main(){
// __builtin_ctz(N); Nを２で何回割り切れるかを返す
//(n+1)*n/2; １からNまでの総和を求める式
    cin.tie(0);
    ios::sync_with_stdio(false);
    int a,w=0;
    int b[100],c[100],d=0,e=0;
    int f=1,g=1;
    itn num[100]={};
    int num2[100]={};
    cin>>a;
    for(int i=0;i<a;i++){
	cin>>b[i];
	num[b[i]]++;
	num2[b[i]]++;
    }
    for(int i=0;i<a;i++){
	cin>>c[i];
    }
    for(int i=a-1;i>=0;i--){
	d+=(b[i]*f);
	f*=10;
    }
    for(int i=a-1;i>=0;i--){
	e+=(c[i]*g);
	g*=10;
    }
    f=0,g=0;
    for(itn i=min(d,e);i<=max(e,d);i++){
	f=i;
	g=0;
	while(true){
	    if(f==0) break;
	    if(num[f%10]>=1){
		num[f%10]--;
	    }
	    else{
		g=1;
		break;
	    }
	    f/=10;
	}
	if(g==0){
	    w++;
	}
	for(int i=0;i<10;i++){
	    num[i]=num2[i];
	}
    }
    cout<<w-1<<"\n";
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i, N, P[9], Q[9];
	scanf("%d", &N);
	for (i = 1; i <= N; i++) scanf("%d", &(P[i]));
	for (i = 1; i <= N; i++) scanf("%d", &(Q[i]));
	
	int j, p = 1, q = 1, fact = 1;
	for (i = 1; i <= N - 1; i++) fact *= i;
	for (i = 1; i <= N - 1; i++) {
		p += (P[i] - 1) * fact;
		q += (Q[i] - 1) * fact;
		for (j = i + 1; j <= N; j++) {
			if (P[j] > P[i]) P[j]--;
			if (Q[j] > Q[i]) Q[j]--;
		}
		fact /= N - i;
	}
	
	printf("%d\n", abs(p - q));
	fflush(stdout);
	return 0;
}
//  [c]
// C - Conunt Order
#include <stdio.h>
#include <stdlib.h>

int cOrder(int n, int a[]){
    int i, j, cnt=0;
    for(i=0; i<n-1; i++){
        for(j=i; j<n; j++){
            if(a[i] > a[j]) cnt++;
        }
        cnt *= n-i-1;
    }
    return cnt;
}

int main(void){
    int n;
    scanf("%d", &n);
    int p[9], q[9];
    for(int i=0; i<n; i++) scanf("%d", &p[i]);
    for(int i=0; i<n; i++) scanf("%d", &q[i]);
    printf("%d\n", abs(cOrder(n, p) - cOrder(n, q)));
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int a=0,b=0,count=0;

void dictionary(int *p,int i,int n,int *P,int *Q){
    int j,k,t;
    if (a!=0&&b!=0) {
        return;
    }
    if (i<n) {
        for (j=i; j<=n; j++) {
            t=p[j];
            for (k=j;k>i; k--) p[k]=p[k-1];
            p[i]=t;
            dictionary(p, i+1,n,P,Q);
            for (k=i; k<j; k++) p[k]=p[k+1];
            p[j]=t;
        }
    }else{
        count++;
        for (j=1; j<=n; j++) if (P[j-1]!=p[j]) break;
        if (j==n+1) a=count;
        for (j=1; j<=n; j++) if (Q[j-1]!=p[j]) break;
        if (j==n+1) b=count;
    }
}

int main(){
    int n,i,dict[10]={};
    int p[10],q[10];
    scanf("%d",&n);
    scanf("%d",&p[0]);
    for (i=1; i<n; i++) scanf(" %d",&p[i]);
    scanf("%d",&q[0]);
    for (i=1; i<n; i++) scanf(" %d",&q[i]);
    for (i=1; i<=n; i++) dict[i]=i;
    dictionary(dict,1,n,p,q);
    if (a-b<0) {
        printf("%d",b-a);
    }else printf("%d",a-b);
    return 0;
}
//  [c]
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
int main() {
	int n, p[8], q[8], t[8], pCnt, qCnt, cnt = 0;
	bool isUse[8], isPerm, isP, isQ;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &p[i]);
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", &q[i]);
	}
	for (int i = 0; i < pow(n, n) - 1; i++) {
		int num = i;
		isPerm = true;
		for (int j = 0; j < n; j++) {
			isUse[j] = false;
		}
		for (int j = 0; j < n; j++) {
			t[j] = num % n + 1;
			isUse[t[j] - 1] = true;
			num /= n;
		}
		for (int j = 0; j < n; j++) {
			if (!isUse[j]) {
				isPerm = false;
				break;
			}
		}
		if (isPerm) {
			cnt++;
			isP = isQ = true;
			for (int j = 0; j < n; j++) {
				if (t[n - j - 1] != p[j]) {
					isP = false;
				}
				if (t[n - j - 1] != q[j]) {
					isQ = false;
				}
				if (!isQ && !isP)
					break;
			}
			if (isP) {
				pCnt = cnt;
			}
			if (isQ) {
				qCnt = cnt;
			}
		}
	}
	printf("%d\n", abs(pCnt - qCnt));
	return 0;
}
//  [c]
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
int main() {
	int n, p[8], q[8], t[8], pCnt, qCnt, cnt = 0;
	bool isUse[8], isPerm, isP, isQ;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &p[i]);
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", &q[i]);
	}
    int l = pow(n, n) - 1;
	for (int i = 0; i < l; i++) {
		int num = i;
		isPerm = true;
		for (int j = 0; j < n; j++) {
			isUse[j] = false;
		}
		for (int j = 0; j < n; j++) {
			t[j] = num % n + 1;
			isUse[t[j] - 1] = true;
			num /= n;
		}
		for (int j = 0; j < n; j++) {
			if (!isUse[j]) {
				isPerm = false;
				break;
			}
		}
		if (isPerm) {
			cnt++;
			isP = isQ = true;
			for (int j = 0; j < n; j++) {
				if (t[n - j - 1] != p[j]) {
					isP = false;
				}
				if (t[n - j - 1] != q[j]) {
					isQ = false;
				}
				if (!isQ && !isP)
					break;
			}
			if (isP) {
				pCnt = cnt;
			}
			if (isQ) {
				qCnt = cnt;
			}
		}
	}
	printf("%d\n", abs(pCnt - qCnt));
	return 0;
}
//  [c]
#include <stdio.h>

int main(void){
    int n;
    scanf("%d", &n);
    int i, j;
    int p[8], q[8];
    for(i = 0; i < n; i++){scanf("%d", &p[i]);}
    for(i = 0; i < n; i++){scanf("%d", &q[i]);}
    for(i = 0; i < n; i++){p[i]--; q[i]--;}
    
    int a_temp[8];

    for(i = 0; i < n; i++){
        a_temp[i] = i;
    }
    int cnt = 1;
    int a, b;
    int flag_a = 0, flag_b = 0;
    int flag;
    int go_next;
    while(1){
        for(i = 0; i < n; i++){
            if(a_temp[i] != p[i]){
                break;
            }
            if(i == n - 1){
                a = cnt;
                flag_a = 1;
            }
        }

        for(i = 0; i < n; i++){
            if(a_temp[i] != q[i]){
                break;
            }
            if(i == n - 1){
                b = cnt;
                flag_b = 1;
            }
        }
        
        if(flag_a == 1 && flag_b == 1){
            break;
        }

        go_next = 0;
        //a_tempを1つ進める処理を書く
        do{
            a_temp[n - 1] += 1;
            for(i = 1; i < n; i++){
                if(a_temp[n - i] == n){
                    a_temp[n - i] = 0;
                    a_temp[n - i - 1]++;
                }
            }
            for(i = 0; i < n; i++){
                flag = 0;
                for(j = 0; j < n; j++){
                    if(a_temp[j] == i){
                        flag = 1;
                        break;
                    }
                }
                if(flag == 0){
                    break;
                }
                if(i == n - 1){
                    go_next = 1;
                }
            }
        }while(go_next == 0);
        cnt++;
    }
    printf("%d\n", a > b ? a - b : b - a);
    
    

}
//  [javascript]
function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    var N = parseInt(input[0], 10);
    var vec_P = input[1].map(e => parseInt(e, 10));
    var vec_Q = input[2].map(e => parseInt(e, 10));
    var pi, qi, a, b;
    a = b = 1;
    for (var i = 0; i < (N - 1); i++){
    	pi = vec_P[0];
    	qi = vec_Q[0];
    	
    	vec_P.shift();
    	vec_Q.shift();
    	a += (N - (i + 1) - countAbove(pi, vec_P)) * kaijo(N - (i + 1));
    	b += (N - (i + 1) - countAbove(qi, vec_Q)) * kaijo(N - (i + 1));
    }
	console.log(Math.abs(a-b));
}

function countAbove(num, vec){
	var ans = 0;
	for (var i = 0; i < vec.length; i++){
		if (vec[i] > num) ans++;
	} 
	return ans;	
}

function kaijo(num){
	var ans = 1;
	for (var i = 2; i <= num; i++){
		ans *= i;
	} 
	return ans;	
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
N = inp.shift() * 1
P = inp.shift().split(' ').map(x => x-0)
Q = inp.shift().split(' ').map(x => x-0)
p = 0
q = 0

for (i=0; i<N; i++) {
    a = 0
    b = 0
    
    x = P[i]

    d = 0
    for (j=i+1; j<N; j++) {
       if (x > P[j]) {
           d++
       }
    }

    if (d > 0) {
        a = 1
        a *= d
        c = 1
        for (x = N - i - 1;x > 1; x--) {
            c *= x
        }
        p += a * c
    }


    x = Q[i]
    d = 0
    for (j=i+1; j<N; j++) {
       if (x > Q[j]) {
           d++
       }
    }

    if (d > 0) {
        a = 1
        a *= d
        c = 1
        for (x = N - i - 1;x > 1; x--) {
            c *= x
        }
        q += a * c
    }
}
console.log(Math.abs(p - q))
//  [javascript]
function Main(input) {
	var lines = input.split("\n");
	var n = lines[0].split(" ").map(el => Number(el))[0]
	var Ps = Number(lines[1].replace(/ /g, ''))
	var Qs = Number(lines[2].replace(/ /g, ''))

	var permutation = (result, pre, post, n) => {
		if (n > 0) {
			post.forEach((_, i) => {
				var rest = [...post];
				var elem = rest.splice(i, 1);
				permutation(result, [...pre, ...elem], rest, n - 1);
			});
		} else {
			result.push(Number(pre.join('')));
		}
		return result;
	};

	var makeArray = n => {
		var rs = []
		for(var i = 1; i <= n; i++) {
			rs.push('' + i)
		}
		return rs
	}

	var p = permutation([], [], makeArray(n), n)
	console.log(Math.abs(p.indexOf(Ps) - p.indexOf(Qs)))
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [javascript]
'use strict';
function* permutation(a,b,n){
  if ( n === 0 ) return yield b;
  for ( let i = 0; i < n; i++ ) {
    const _a = [...a];
    const c = _a.splice(i,1)[0];
    yield* permutation(_a, [...b,c], n-1);
  }
}
console.log(function(args){
  const _tmp = args.trim().split('\n');
  const N = _tmp[0]|0;
  const P = _tmp[1].split(' ').map(v=>v|0);
  const Q = _tmp[2].split(' ').map(v=>v|0);
  let a = 0, b = 0, c = 0;
  const O = Array(N).fill(0).map((a,i)=>i+1);
  for ( let o of permutation(O,[],N) ) {
    c++;
    if ( o.every((v,i)=>v===P[i]) ) a = c;
    if ( o.every((v,i)=>v===Q[i]) ) b = c;
    if ( a && b ) break;
  }
  return Math.abs(a-b).toString();
}(require('fs').readFileSync('/dev/stdin', 'utf8')));
//  [javascript]
"use strict";
main(
  require("fs")
    .readFileSync("/dev/stdin", "UTF-8")
    .trim()
    .split("\n")
);

/**
 *
 * 大きさNの順列。(1, 2, ..., N)を並び替えて出来る順列P, Q
 * 順列はN!通り存在する。
 * Pがa番目に小さく、Qがb番目に小さいとした時、|a-b|を求めよ
 */

function permutation(nums, k) {
  let ans = [];
  if (nums.length < k) {
    return [];
  }
  if (k === 1) {
    for (let i = 0; i < nums.length; i++) {
      ans[i] = [nums[i]];
    }
  } else {
    for (let i = 0; i < nums.length; i++) {
      let parts = nums.slice(0);
      parts.splice(i, 1)[0];
      let row = permutation(parts, k - 1);
      for (let j = 0; j < row.length; j++) {
        ans.push([nums[i]].concat(row[j]));
      }
    }
  }
  return ans;
}

function main(input) {
  const N = Number(input.shift());
  let P = input[0].split(" ");
  let Q = input[1].split(" ");

  const num = permutation(P.slice().sort(), P.length);
  for (let i = 0; i < num.length; i++) {
    if (JSON.stringify(P) === JSON.stringify(num[i])) {
      P = i;
    }
    if (JSON.stringify(Q) === JSON.stringify(num[i])) {
      Q = i;
    }
  }

  console.log(Math.abs(P - Q));
}
//  [go]
package main

import "fmt"

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

func factorial(n int) int {
	v := 1
	for i := 2; i <= n; i++ {
		v *= i
	}
	return v
}

func rank(a []int, n int) int {
	r := 0

	appear := make([]bool, n)

	for i, v := range a[:n-1] {
		appear[v-1] = true

		rem_rank := 0
		for j := 0; j < v-1; j++ {
			if !appear[j] {
				rem_rank++
			}
		}

		r += rem_rank * factorial(n-i-1)
	}
	return r + 1
}

func main() {
	var N int
	fmt.Scan(&N)
	P := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&P[i])
	}
	Q := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&Q[i])
	}
	a := rank(P, N)
	b := rank(Q, N)
	fmt.Println(abs(a - b))
}
//  [go]
package main

import (
	"fmt"
)

func fact(x int) int {
	res := 1
	for x > 0 {
		res *= x
		x--
	}
	return res
}

func dictorder(array []int) int {
	res, length := 1, len(array)
	done := make([]int, length+1)
	for i, x := range array {
		t := 0
		for y := 1; y < x; y++ {
			if done[y] == 0 {
				t++
			}
		}
		res += fact(length-i-1) * t
		done[x] = 1
	}
	return res
}

func abs(x int) int {
	if x > 0 {
		return x
	} else {
		return -x
	}
}

func main() {
	var n int
	fmt.Scan(&n)
	p := make([]int, n)
	for i := range p {
		fmt.Scan(&p[i])
	}
	q := make([]int, n)
	for i := range q {
		fmt.Scan(&q[i])
	}
	fmt.Println(abs(dictorder(p) - dictorder(q)))
}
//  [go]
package main

import "fmt"

func main() {
	p, q := input()
	a := sub(permitationNumber(p), permitationNumber(q))
	fmt.Println(a)
}

func sub(p, q int) int {
	if p < q {
		return q - p
	}
	return p - q
}

func permitationNumber(n []int) int {
	if len(n) <= 1 {
		return 0
	}
	return permitationNumber(n[1:]) + minNumber(n[0], n[1:])*factorial(len(n)-1)
}

func minNumber(m int, n []int) int {
	c := 0
	for _, v := range n {
		if v < m {
			c++
		}
	}
	return c
}

func factorial(n int) int {
	s := 1
	for ; n > 1; n-- {
		s *= n
	}
	return s
}

func input() ([]int, []int) {
	var n int
	fmt.Scan(&n)
	p := make([]int, n, n)
	q := make([]int, n, n)
	for i := range p {
		fmt.Scan(&p[i])
	}
	for i := range q {
		fmt.Scan(&q[i])
	}
	return p, q
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func Scan() string {
	sc.Scan()
	return sc.Text()
}
func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}
func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := iScan()
	p := iSScan(n)
	q := iSScan(n)
	r := make([]int, n)
	copy(r, p)
	perm := Permute(r)
	for x := n - 1; x >= 0; x-- {
		sort.SliceStable(perm, func(i, j int) bool { return perm[i][x] < perm[j][x] })
	}
	a, b := -1, -1
	for i, v := range perm {
		if fmt.Sprint(p) == fmt.Sprint(v) {
			a = i
		}
		if fmt.Sprint(q) == fmt.Sprint(v) {
			b = i
		}
	}
	fmt.Println(abs(a - b))
}
func Permute(nums []int) [][]int {
	n := factorial(len(nums))
	ret := make([][]int, 0, n)
	permute(nums, &ret)
	return ret
}

func permute(nums []int, ret *[][]int) {
	*ret = append(*ret, makeCopy(nums))
	n := len(nums)
	p := make([]int, n+1)
	for i := 0; i < n+1; i++ {
		p[i] = i
	}
	for i := 1; i < n; {
		p[i]--
		j := 0
		if i%2 == 1 {
			j = p[i]
		}

		nums[i], nums[j] = nums[j], nums[i]
		*ret = append(*ret, makeCopy(nums))
		for i = 1; p[i] == 0; i++ {
			p[i] = i
		}
	}
}

func factorial(n int) int {
	ret := 1
	for i := 2; i <= n; i++ {
		ret *= i
	}
	return ret
}

func makeCopy(nums []int) []int {
	return append([]int{}, nums...)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func factorial(n int) int {
	if n == 1 {
		return 1
	}
	return factorial(n-1) * n
}

func makeCopy(nums []int) []int {
	return append([]int{}, nums...)
}

func permute(nums []int, ret *[][]int) {
	*ret = append(*ret, makeCopy(nums))

	n := len(nums)
	p := make([]int, n+1)
	for i := 0; i < n+1; i++ {
		p[i] = i
	}
	for i := 1; i < n; {
		p[i]--
		j := 0
		if i%2 == 1 {
			j = p[i]
		}

		nums[i], nums[j] = nums[j], nums[i]
		*ret = append(*ret, makeCopy(nums))
		for i = 1; p[i] == 0; i++ {
			p[i] = i
		}
	}
}

func permutation(nums []int) [][]int {
	n := factorial(len(nums))
	ret := make([][]int, 0, n)
	permute(nums, &ret)
	return ret
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func main() {
	var n int
	fmt.Scan(&n)
	p := make([]int, n)
	q := make([]int, n)
	for i := range p {
		fmt.Scan(&p[i])
	}
	for i := range q {
		fmt.Scan(&q[i])
	}

	nums := make([]int, n)
	for i := 1; i <= n; i++ {
		nums[i-1] = i
	}

	var pattern []string
	for _, v := range permutation(nums) {
		pattern = append(pattern, fmt.Sprint(v))
	}
	sort.Strings(pattern)

	var a, b int
	for i, v := range pattern {
		if v == fmt.Sprint(p) {
			a = i + 1
		}
		if v == fmt.Sprint(q) {
			b = i + 1
		}
	}
	fmt.Println(abs(a - b))
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func factorial(n int) int {
	if n == 1 {
		return 1
	}
	return factorial(n-1) * n
}

func makeCopy(nums []int) []int {
	return append([]int{}, nums...)
}

func permute(nums []int, ret *[]string) {
	*ret = append(*ret, fmt.Sprint(makeCopy(nums)))

	n := len(nums)
	p := make([]int, n+1)
	for i := 0; i < n+1; i++ {
		p[i] = i
	}
	for i := 1; i < n; {
		p[i]--
		j := 0
		if i%2 == 1 {
			j = p[i]
		}

		nums[i], nums[j] = nums[j], nums[i]
		*ret = append(*ret, fmt.Sprint(makeCopy(nums)))
		for i = 1; p[i] == 0; i++ {
			p[i] = i
		}
	}
}

func permutation(nums []int) []string {
	n := factorial(len(nums))
	ret := make([]string, 0, n)
	permute(nums, &ret)
	return ret
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func main() {
	var n int
	fmt.Scan(&n)
	p := make([]int, n)
	q := make([]int, n)
	for i := range p {
		fmt.Scan(&p[i])
	}
	for i := range q {
		fmt.Scan(&q[i])
	}

	nums := make([]int, n)
	for i := 1; i <= n; i++ {
		nums[i-1] = i
	}

	pattern := permutation(nums)
	sort.Strings(pattern)

	var a, b int
	for i, v := range pattern {
		if v == fmt.Sprint(p) {
			a = i + 1
		}
		if v == fmt.Sprint(q) {
			b = i + 1
		}
	}
	fmt.Println(abs(a - b))
}
//  [ruby]
N = gets.to_i

# 1! ～ (N-1)! までを計算する
$kai = [1]
(N-2).times do |i|
  $kai.unshift($kai[0] * (i+2))
end
#p $kai

A = gets.split(' ').map(&:to_i)
B = gets.split(' ').map(&:to_i)

def n_banme(x)
  indexes = []
  N.times do |i|
    indexes << i+1
  end
  #print 'indexes = '
  #p indexes
  #p x
  ans = 0
  
  (N-1).times do |i|
    # puts 'i = '+ i.to_s
    # 順番未確定の数値のなかで何番目に大きいか
    idx = indexes.index(x[i])
    # puts 'idx = ' + idx.to_s
    ans += idx * $kai[i]
    # puts 'ans = '+ ans.to_s
    indexes.delete_at(idx)
  end
  ans += 1
  # puts 'final_ans = '+ans.to_s
  return ans
end

a = n_banme(A)
b = n_banme(B)
# puts a,b
puts (a-b).abs
//  [ruby]
# https://atcoder.jp/contests/abc150/tasks/abc150_c

def init_fact(n)
  @fact = Array.new(n + 1)
  @fact[0] = 1
  n.times { |i| @fact[i + 1] = @fact[i] * (i + 1) }
end

def order(ps)
  order2((1..ps.size).to_a, ps)
end

def order2(as, ps)
  return 0 if as.size == 0
  i = ps[0]
  ret = as.index(i) * @fact[as.size - 1]
  as.delete(i)
  ps.delete(i)
  ret + order2(as, ps)
end

N = gets.to_i
Ps = gets.split.map(&:to_i)
Qs = gets.split.map(&:to_i)

init_fact(N)
a = order(Ps)
b = order(Qs)
puts (a - b).abs
//  [ruby]
N = gets.chomp.to_i
str = gets.split
a = Array.new(N)
for i in 0...N do
    a[i] = str[i].to_i
end
str = gets.split
b = Array.new(N)
for i in 0...N do
    b[i] = str[i].to_i
end
c = Array.new(N,1)
for i in 1...N do
    c[N-1-i] = c[N-i]*i
end
d = Array.new(0)
for i in 1..N do
    d.push(i)
end
e = Array.new(0)
for i in 1..N do
    e.push(i)
end

f = 1
i = 0
while d.size >= 2
    x = a[i]
    j = 0
    while x != d[j]
       j += 1 
    end
    f += c[i]*j
    d.delete_at(j)
    i += 1
end
g = 1
i = 0
while e.size >= 2
    x = b[i]
    j = 0
    while x != e[j]
       j += 1 
    end
    g += c[i]*j
    e.delete_at(j)
    i += 1
end

answer = (f-g).abs
puts answer
//  [ruby]
# matrixの基本操作

def same_el(array_)
  if array_.kind_of?(Array)
    output = []
    for i in  0..(array_.count-1)
      output.push(array_[i])
    end
  end
  return output
end

# ---------------------------------------------

def replace(n)

  sgn=[]
  remain=[]
  output=[] #n!個の要素を持つ配列を返す
  for i in 0..n
    sgn << i
    remain << i
  end
  output << []
  for i in 0..n
    output[0] << i
  end

  while true
    remain_act = same_el(remain)
    remain_act.delete(0)
    for i in 1..n-1
      judge_order = true
      for j in i+1..n-1
        sgn[j]<sgn[j+1] && judge_order = false
      end
      judge_order && break
      remain_act.delete(sgn[i])
    end
    singular = i
    remain_act.sort!
    for i in 0..n-(singular-2)
      if sgn[singular] == remain_act[i]
        sgn[singular] = remain_act[i+1]
        break
      end
    end
    remain_act.delete(sgn[singular])
    for i in singular+1..n
      sgn[i] = remain_act[i-(singular+1)]
    end
    inp =same_el(sgn)
    output << inp
    lastmat=true
    for i in 1..n
      sgn[i] != n+1-i && lastmat=false
    end
    lastmat && break
  end

  for i in 0..output.count-1
    output[i].delete(0)
  end
  output
end

# ---------------------------------------------

def signal(replaces)
  output = Array.new
  index = Array.new

  replace.size.times do |i|
    for j in 0..replaces.size-1
      index[j] = j+1
    end
    i_op = i.clone
    while true
      j = 0
      nimotu = index[0]
      sgn_part = -1
      while true
        if i_op[j] == nimotu

        else
        end
      end

    end
    output << sgn
  end
end

N=gets.to_i
ar=replace(N)
ps=gets.split.map(&:to_i)
qs=gets.split.map(&:to_i)
p (ar.index(ps)-ar.index(qs)).abs
//  [ruby]
def solve(n, id, ln, ar)
  ar[id] = n
  if id == ln-1
    @cnt += 1
    pif = qif = 1
    for i in 0..(ln-1)
      pif = 0 if ar[i] != @p[i]
      qif = 0 if ar[i] != @q[i]
    end
    @pod = @cnt if pif == 1
    @qod = @cnt if qif == 1
    return
  end
  
  for i in 1..ln
    flag = 1
    for j in 0..id
      if ar[j] == i
        flag = 0
        break
      end
    end
    solve(i, id+1, ln, ar) if flag == 1
  end
end

n = gets.to_i
@p = gets.split.map(&:to_i)
@q = gets.split.map(&:to_i)

@cnt = 0
@pod = @qod = -1
for i in 1..n
  ar = Array.new(n)
  solve(i, 0, n, ar)
end
puts (@pod-@qod).abs