PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#CC0000018. Đếm bộ ba giữ nguyên thứ tự trong hai hoán vị (Count Good Triplets in an Array)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

2 lộ trình

Đếm bộ ba giữ nguyên thứ tự trong hai hoán vị (Count Good Triplets in an Array)

Count Good Triplets in an Array

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given two permutations pp and qq of 0,1,…,n−10,1,\ldots,n-1. Choose three distinct values x,y,zx,y,z. The triple is good if xx occurs before yy and yy before zz in both permutations. Count all good triples. This concerns positions, not numeric ordering of the chosen values.

Input

The first line contains nn. The second contains permutation p1,…,pnp_1,\ldots,p_n. The third contains permutation q1,…,qnq_1,\ldots,q_n. Each is a permutation of 0,1,…,n−10,1,\ldots,n-1.

Output

Print one 64-bit integer: the number of triples of values appearing in the same order in both permutations.

Subtasks

  • Subtask 1 (20 points): 3≤n≤103\le n\le 10; each of pp and qq is a permutation of 0,1,…,n−10,1,\ldots,n-1.
  • Subtask 2 (30 points): 3≤n≤9003\le n\le 900; each of pp and qq is a permutation of 0,1,…,n−10,1,\ldots,n-1.
  • Subtask 3 (50 points): 3≤n≤1000003\le n\le 100000; each of pp and qq is a permutation of 0,1,…,n−10,1,\ldots,n-1.

Examples

Input

4
2 0 1 3
0 1 2 3

Output

1

Explanation

The first permutation has four ordered triples: (2,0,1)(2,0,1), (2,0,3)(2,0,3), (2,1,3)(2,1,3), and (0,1,3)(0,1,3). Only (0,1,3)(0,1,3) appears in that same order in the second permutation. The answer is 11.