exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
2b2e987132460071ff48137f60830d95
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.*; public class P1678A { public static void main(String[] args) throws Exception { new P1678A().run(); } void run() throws Exception { Scanner scanner = new Scanner(getInputStream()); int t = scanner.nextInt(); while(t-- > 0) { int n = scanner.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } getOutputStream().println(getMinOps(a)); } } private int getMinOps(int[] a) { Arrays.sort(a); int nonZeros = 0; for(int av : a) { if (av != 0) { nonZeros++; } } if (a[0] == 0) { return nonZeros; } boolean hasSame = false; for(int i = 0; i < a.length - 1; i++) { if (a[i] == a[i+1]) { hasSame = true; break; } } if (hasSame) { return a.length; } else { return a.length + 1; } } InputStream getInputStream() { return System.in; } PrintStream getOutputStream() { return System.out; } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
dd04d440c3d379665f314849008a5b77
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import java.util.Scanner; public class T1678A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int a[] = new int[101]; //карманная сортировка for (int j = 0; j < n; j++) { a[in.nextInt()]++; } int result = 0; if (a[0] > 0) { result = n - a[0]; } else { boolean isEquals = false; for (int j = 0; j < a.length; j++) { if (a[j] > 1) { isEquals = true; break; } } if (isEquals) { result = n; } else { result = n + 1; } } System.out.println(result); } } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
97834ea4f4e7ed2b0c8ddf55fac6ca0b
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc=new FastReader(); // static long dp[][]; // static boolean v[][][]; // static int mod=998244353;; // static int mod=1000000007; static long oset[]; static int oset_p; static long mod=1000000007; // static int max; static int bit[]; //static long fact[]; //static HashMap<Long,Long> mp; //static StringBuffer sb=new StringBuffer(""); //static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); long a[]=inputL(n); Map<Long,Long>map=hash(a); if(map.containsKey((long)0)) { out.println(n-map.get((long)0)); } else { for(long it:map.keySet()) { if(map.get(it)>1) { out.println(n); continue outer;} } out.println(n+1); } } out.close(); } static class Pair implements Comparable<Pair> { int x; int y; // int z; Pair(int x,int y){ this.x=x; this.y=y; // this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair other = (Pair)o; if (this.x != other.x || this.y!=other.y) { return false; } return true; } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static long summation(long A[],int si,int ei) { long ans=0; for(int i=si;i<=ei;i++) ans+=A[i]; return ans; } static void add(long v,Map<Long,Long>mp) { if(!mp.containsKey(v)) { mp.put(v, (long)1); } else { mp.put(v, mp.get(v)+(long)1); } } static void remove(long v,Map<Long,Long>mp) { if(mp.containsKey(v)) { mp.put(v, mp.get(v)-(long)1); if(mp.get(v)==0) mp.remove(v); } } public static int upper(long A[],long k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(long A[],long k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static long[][] input(int n,int m){ long A[][]=new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=l(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { if(n==0) return 1; n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { out.print(i+" "); } out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Long> hash(int A[]){ HashMap<Integer,Long> map=new HashMap<Integer, Long>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+(long)1); } else { map.put(i, (long)1); } } return map; } static HashMap<Long,Long> hash(long A[]){ HashMap<Long,Long> map=new HashMap<Long, Long>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+(long)1); } else { map.put(i, (long)1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
16178c7a495551f32dffd6da9448eddd
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class A { public static void process() throws IOException { int n = sc.nextInt(); int arr[] = sc.readArray(n); ruffleSort(arr); int ans = n; for(int e : arr) { if(e == 0)ans--; } if(ans != n) { System.out.println(ans); return; } for(int i = 0; i+1<n; i++) { if(arr[i] == arr[i+1]) { System.out.println(n); return; } } System.out.println(n+1); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
ec7683104a31777e53dd9075167d69a5
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.util.*; public class Main { public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static int findMax(int a[], int n, int vis[], int i, int d){ if(i>=n) return 0; if(vis[i]==1) return findMax(a, n, vis, i+1, d); int max = 0; for(int j=i+1;j<n;j++){ if(Math.abs(a[i]-a[j])>d||vis[j]==1) continue; vis[j] = 1; max = Math.max(max, 1 + findMax(a, n, vis, i+1, d)); vis[j] = 0; } return max; } static void findSub(ArrayList<ArrayList<Integer>> ar, int n, ArrayList<Integer> a, int i){ if(i==n){ ArrayList<Integer> b = new ArrayList<Integer>(); for(int y:a){ b.add(y); } ar.add(b); return; } for(int j=0;j<n;j++){ if(j==i) continue; a.set(i,j); findSub(ar, n, a, i+1); } } // *-------------------code starts here--------------------------------------------------* static HashMap<Long,Integer>map; public static void solve(InputReader sc, PrintWriter pw){ long mod=(long)1e9+7; int t=sc.nextInt(); // int t=1; L : while(--t>=0){ int n=sc.nextInt(); int a[]=sc.readArray(n); sort(a); if(a[0]==0){ int cnt=0; for(int i=0;i<n;i++){ if(a[i]!=0){ cnt++; } } pw.println(cnt); } else{ HashSet<Integer> set=new HashSet<>(); for(int i=0;i<n;i++){ set.add(a[i]); } if(set.size()!=n){ pw.println(n); } else{ pw.println(n+1); } } } } // *-------------------code ends here-----------------------------------------------------* static void assignAnc(ArrayList<Integer> ar[],int sz[], int pa[] ,int curr, int par){ sz[curr] = 1; pa[curr] = par; for(int v:ar[curr]){ if(par==v) continue; assignAnc(ar, sz, pa, v, curr); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static class Pair implements Comparable<Pair> { int a; int b; // int c; Pair(int a, int b) { this.a = a; this.b = b; // this.c = c; } public int compareTo(Pair p) { return Integer.compare(a,p.a); } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } public long[] readarray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
5efd4f0572bb1003b4eea85e7c55fa87
train_108.jsonl
1652020500
Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$). If $$$a_i = a_j$$$, change one of them to $$$0$$$. Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class A1678 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); boolean same = false; int nonZero = 0; Set<Integer> set = new HashSet<>(); for (int n=0; n<N; n++) { int a = in.nextInt(); if (!set.add(a)) { same = true; } if (a != 0) { nonZero++; } } int answer; if (nonZero != N) { answer = nonZero; } else { answer = same ? N : (N+1); } System.out.println(answer); } } }
Java
["3\n3\n1 2 3\n3\n1 2 2\n3\n1 2 0"]
1 second
["4\n3\n2"]
NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 &lt; a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 &lt; a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.
Java 8
standard input
[ "implementation" ]
ad242f98f1c8eb8d30789ec672fc95a0
The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.
800
For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.
standard output
PASSED
a2fccebaa09166eaa2a0ccfc76505869
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; /** * * @author eslam */ public class IceCave { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // Beginning of the solution static FastReader input = new FastReader(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Long>> powerSet = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static boolean ca = true; static int dp[]; public static void main(String[] args) throws IOException { int t = input.nextInt(); while (t-- > 0) { int n = input.nextInt(); int a[] = new int[n]; long fans = 0; for (int i = 0; i < n; i++) { a[i] = input.nextInt()-1; } int ans[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { ans[a[i]][j] = 1; } } } for (int i = 0; i < n; i++) { suffixSum(ans[i]); } for (int i = 0; i < n-1; i++) { int b = 0; for (int j = 0; j < i; j++) { long an = ans[a[j]][i+1]; fans += (b) * an; if (a[j] < a[i]) { b++; } } } log.write(fans + "\n"); } log.flush(); } public static void graphRepresintionWithCycle(ArrayList<Integer>[] a, int q) { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static void dfsRecursive(int n, ArrayList<Integer>[] a, boolean visited[]) { ArrayList<Integer> nodes = a[n]; visited[n] = true; for (Integer node : nodes) { if (!visited[node]) { dfsRecursive(node, a, visited); } } } public static int get(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } public static int primeFactors(int n) { int sum = 0; while (n % 2 == 0) { sum += 2; n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { sum += get(i); n /= i; } if (n < i) { break; } } if (n > 2) { sum += get(n); } return sum; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } public static void genrate(int ind, long[] a, ArrayList<Long> sub) { if (ind == a.length) { powerSet.add(sub); return; } ArrayList<Long> have = new ArrayList<>(); ArrayList<Long> less = new ArrayList<>(); for (int i = 0; i < sub.size(); i++) { have.add(sub.get(i)); less.add(sub.get(i)); } have.add(a[ind]); genrate(ind + 1, a, have); genrate(ind + 1, a, less); } // end of solution public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n *= t; t--; } return n; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(int[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void print(int a[]) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class pair { long x; int y; public pair(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(long a, long b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } /** */ // class RedBlackNode static class RedBlackNode<T extends Comparable<T>> { /** * Possible color for this node */ public static final int BLACK = 0; /** * Possible color for this node */ public static final int RED = 1; // the key of each node public T key; /** * Parent of node */ RedBlackNode<T> parent; /** * Left child */ RedBlackNode<T> left; /** * Right child */ RedBlackNode<T> right; // the number of elements to the left of each node public int numLeft = 0; // the number of elements to the right of each node public int numRight = 0; // the color of a node public int color; RedBlackNode() { color = BLACK; numLeft = 0; numRight = 0; parent = null; left = null; right = null; } // Constructor which sets key to the argument. RedBlackNode(T key) { this(); this.key = key; } }// end class RedBlackNode static class RedBlackTree<T extends Comparable<T>> { // Root initialized to nil. private RedBlackNode<T> nil = new RedBlackNode<T>(); private RedBlackNode<T> root = nil; public RedBlackTree() { root.left = nil; root.right = nil; root.parent = nil; } // @param: x, The node which the lefRotate is to be performed on. // Performs a leftRotate around x. private void leftRotate(RedBlackNode<T> x) { // Call leftRotateFixup() which updates the numLeft // and numRight values. leftRotateFixup(x); // Perform the left rotate as described in the algorithm // in the course text. RedBlackNode<T> y; y = x.right; x.right = y.left; // Check for existence of y.left and make pointer changes if (!isNil(y.left)) { y.left.parent = x; } y.parent = x.parent; // x's parent is nul if (isNil(x.parent)) { root = y; } // x is the left child of it's parent else if (x.parent.left == x) { x.parent.left = y; } // x is the right child of it's parent. else { x.parent.right = y; } // Finish of the leftRotate y.left = x; x.parent = y; }// end leftRotate(RedBlackNode x) // @param: x, The node which the leftRotate is to be performed on. // Updates the numLeft & numRight values affected by leftRotate. private void leftRotateFixup(RedBlackNode x) { // Case 1: Only x, x.right and x.right.right always are not nil. if (isNil(x.left) && isNil(x.right.left)) { x.numLeft = 0; x.numRight = 0; x.right.numLeft = 1; } // Case 2: x.right.left also exists in addition to Case 1 else if (isNil(x.left) && !isNil(x.right.left)) { x.numLeft = 0; x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 2 + x.right.left.numLeft + x.right.left.numRight; } // Case 3: x.left also exists in addition to Case 1 else if (!isNil(x.left) && isNil(x.right.left)) { x.numRight = 0; x.right.numLeft = 2 + x.left.numLeft + x.left.numRight; } // Case 4: x.left and x.right.left both exist in addtion to Case 1 else { x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 3 + x.left.numLeft + x.left.numRight + x.right.left.numLeft + x.right.left.numRight; } }// end leftRotateFixup(RedBlackNode x) // @param: x, The node which the rightRotate is to be performed on. // Updates the numLeft and numRight values affected by the Rotate. private void rightRotate(RedBlackNode<T> y) { // Call rightRotateFixup to adjust numRight and numLeft values rightRotateFixup(y); // Perform the rotate as described in the course text. RedBlackNode<T> x = y.left; y.left = x.right; // Check for existence of x.right if (!isNil(x.right)) { x.right.parent = y; } x.parent = y.parent; // y.parent is nil if (isNil(y.parent)) { root = x; } // y is a right child of it's parent. else if (y.parent.right == y) { y.parent.right = x; } // y is a left child of it's parent. else { y.parent.left = x; } x.right = y; y.parent = x; }// end rightRotate(RedBlackNode y) // @param: y, the node around which the righRotate is to be performed. // Updates the numLeft and numRight values affected by the rotate private void rightRotateFixup(RedBlackNode y) { // Case 1: Only y, y.left and y.left.left exists. if (isNil(y.right) && isNil(y.left.right)) { y.numRight = 0; y.numLeft = 0; y.left.numRight = 1; } // Case 2: y.left.right also exists in addition to Case 1 else if (isNil(y.right) && !isNil(y.left.right)) { y.numRight = 0; y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 2 + y.left.right.numRight + y.left.right.numLeft; } // Case 3: y.right also exists in addition to Case 1 else if (!isNil(y.right) && isNil(y.left.right)) { y.numLeft = 0; y.left.numRight = 2 + y.right.numRight + y.right.numLeft; } // Case 4: y.right & y.left.right exist in addition to Case 1 else { y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 3 + y.right.numRight + y.right.numLeft + y.left.right.numRight + y.left.right.numLeft; } }// end rightRotateFixup(RedBlackNode y) public void insert(T key) { insert(new RedBlackNode<T>(key)); } // @param: z, the node to be inserted into the Tree rooted at root // Inserts z into the appropriate position in the RedBlackTree while // updating numLeft and numRight values. private void insert(RedBlackNode<T> z) { // Create a reference to root & initialize a node to nil RedBlackNode<T> y = nil; RedBlackNode<T> x = root; // While we haven't reached a the end of the tree keep // tryint to figure out where z should go while (!isNil(x)) { y = x; // if z.key is < than the current key, go left if (z.key.compareTo(x.key) < 0) { // Update x.numLeft as z is < than x x.numLeft++; x = x.left; } // else z.key >= x.key so go right. else { // Update x.numGreater as z is => x x.numRight++; x = x.right; } } // y will hold z's parent z.parent = y; // Depending on the value of y.key, put z as the left or // right child of y if (isNil(y)) { root = z; } else if (z.key.compareTo(y.key) < 0) { y.left = z; } else { y.right = z; } // Initialize z's children to nil and z's color to red z.left = nil; z.right = nil; z.color = RedBlackNode.RED; // Call insertFixup(z) insertFixup(z); }// end insert(RedBlackNode z) // @param: z, the node which was inserted and may have caused a violation // of the RedBlackTree properties // Fixes up the violation of the RedBlackTree properties that may have // been caused during insert(z) private void insertFixup(RedBlackNode<T> z) { RedBlackNode<T> y = nil; // While there is a violation of the RedBlackTree properties.. while (z.parent.color == RedBlackNode.RED) { // If z's parent is the the left child of it's parent. if (z.parent == z.parent.parent.left) { // Initialize y to z 's cousin y = z.parent.parent.right; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black & z is a right child else if (z == z.parent.right) { // leftRotaet around z's parent z = z.parent; leftRotate(z); } // Case 3: else y is black & z is a left child else { // recolor and rotate round z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; rightRotate(z.parent.parent); } } // If z's parent is the right child of it's parent. else { // Initialize y to z's cousin y = z.parent.parent.left; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black and z is a left child else if (z == z.parent.left) { // rightRotate around z's parent z = z.parent; rightRotate(z); } // Case 3: if y is black and z is a right child else { // recolor and rotate around z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; leftRotate(z.parent.parent); } } } // Color root black at all times root.color = RedBlackNode.BLACK; }// end insertFixup(RedBlackNode z) // @param: node, a RedBlackNode // @param: node, the node with the smallest key rooted at node public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) { // while there is a smaller key, keep going left while (!isNil(node.left)) { node = node.left; } return node; }// end treeMinimum(RedBlackNode node) // @param: x, a RedBlackNode whose successor we must find // @return: return's the node the with the next largest key // from x.key public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) { // if x.left is not nil, call treeMinimum(x.right) and // return it's value if (!isNil(x.left)) { return treeMinimum(x.right); } RedBlackNode<T> y = x.parent; // while x is it's parent's right child... while (!isNil(y) && x == y.right) { // Keep moving up in the tree x = y; y = y.parent; } // Return successor return y; }// end treeMinimum(RedBlackNode x) // @param: z, the RedBlackNode which is to be removed from the the tree // Remove's z from the RedBlackTree rooted at root public void remove(RedBlackNode<T> v) { RedBlackNode<T> z = search(v.key); // Declare variables RedBlackNode<T> x = nil; RedBlackNode<T> y = nil; // if either one of z's children is nil, then we must remove z if (isNil(z.left) || isNil(z.right)) { y = z; } // else we must remove the successor of z else { y = treeSuccessor(z); } // Let x be the left or right child of y (y can only have one child) if (!isNil(y.left)) { x = y.left; } else { x = y.right; } // link x's parent to y's parent x.parent = y.parent; // If y's parent is nil, then x is the root if (isNil(y.parent)) { root = x; } // else if y is a left child, set x to be y's left sibling else if (!isNil(y.parent.left) && y.parent.left == y) { y.parent.left = x; } // else if y is a right child, set x to be y's right sibling else if (!isNil(y.parent.right) && y.parent.right == y) { y.parent.right = x; } // if y != z, trasfer y's satellite data into z. if (y != z) { z.key = y.key; } // Update the numLeft and numRight numbers which might need // updating due to the deletion of z.key. fixNodeData(x, y); // If y's color is black, it is a violation of the // RedBlackTree properties so call removeFixup() if (y.color == RedBlackNode.BLACK) { removeFixup(x); } }// end remove(RedBlackNode z) // @param: y, the RedBlackNode which was actually deleted from the tree // @param: key, the value of the key that used to be in y private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) { // Initialize two variables which will help us traverse the tree RedBlackNode<T> current = nil; RedBlackNode<T> track = nil; // if x is nil, then we will start updating at y.parent // Set track to y, y.parent's child if (isNil(x)) { current = y.parent; track = y; } // if x is not nil, then we start updating at x.parent // Set track to x, x.parent's child else { current = x.parent; track = x; } // while we haven't reached the root while (!isNil(current)) { // if the node we deleted has a different key than // the current node if (y.key != current.key) { // if the node we deleted is greater than // current.key then decrement current.numRight if (y.key.compareTo(current.key) > 0) { current.numRight--; } // if the node we deleted is less than // current.key thendecrement current.numLeft if (y.key.compareTo(current.key) < 0) { current.numLeft--; } } // if the node we deleted has the same key as the // current node we are checking else { // the cases where the current node has any nil // children and update appropriately if (isNil(current.left)) { current.numLeft--; } else if (isNil(current.right)) { current.numRight--; } // the cases where current has two children and // we must determine whether track is it's left // or right child and update appropriately else if (track == current.right) { current.numRight--; } else if (track == current.left) { current.numLeft--; } } // update track and current track = current; current = current.parent; } }//end fixNodeData() // @param: x, the child of the deleted node from remove(RedBlackNode v) // Restores the Red Black properties that may have been violated during // the removal of a node in remove(RedBlackNode v) private void removeFixup(RedBlackNode<T> x) { RedBlackNode<T> w; // While we haven't fixed the tree completely... while (x != root && x.color == RedBlackNode.BLACK) { // if x is it's parent's left child if (x == x.parent.left) { // set w = x's sibling w = x.parent.right; // Case 1, w's color is red. if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; leftRotate(x.parent); w = x.parent.right; } // Case 2, both of w's children are black if (w.left.color == RedBlackNode.BLACK && w.right.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's right child is black if (w.right.color == RedBlackNode.BLACK) { w.left.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; rightRotate(w); w = x.parent.right; } // Case 4, w = black, w.right = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.right.color = RedBlackNode.BLACK; leftRotate(x.parent); x = root; } } // if x is it's parent's right child else { // set w to x's sibling w = x.parent.left; // Case 1, w's color is red if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; rightRotate(x.parent); w = x.parent.left; } // Case 2, both of w's children are black if (w.right.color == RedBlackNode.BLACK && w.left.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's left child is black if (w.left.color == RedBlackNode.BLACK) { w.right.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; leftRotate(w); w = x.parent.left; } // Case 4, w = black, and w.left = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.left.color = RedBlackNode.BLACK; rightRotate(x.parent); x = root; } } }// end while // set x to black to ensure there is no violation of // RedBlack tree Properties x.color = RedBlackNode.BLACK; }// end removeFixup(RedBlackNode x) // @param: key, the key whose node we want to search for // @return: returns a node with the key, key, if not found, returns null // Searches for a node with key k and returns the first such node, if no // such node is found returns null public RedBlackNode<T> search(T key) { // Initialize a pointer to the root to traverse the tree RedBlackNode<T> current = root; // While we haven't reached the end of the tree while (!isNil(current)) { // If we have found a node with a key equal to key if (current.key.equals(key)) // return that node and exit search(int) { return current; } // go left or right based on value of current and key else if (current.key.compareTo(key) < 0) { current = current.right; } // go left or right based on value of current and key else { current = current.left; } } // we have not found a node whose key is "key" return null; }// end search(int key) // @param: key, any Comparable object // @return: return's the number of elements greater than key public int numGreater(T key) { // Call findNumGreater(root, key) which will return the number // of nodes whose key is greater than key return findNumGreater(root, key); }// end numGreater(int key) // @param: key, any Comparable object // @return: return's teh number of elements smaller than key public int numSmaller(T key) { // Call findNumSmaller(root,key) which will return // the number of nodes whose key is greater than key return findNumSmaller(root, key); }// end numSmaller(int key) // @param: node, the root of the tree, the key who we must // compare other node key's to. // @return: the number of nodes greater than key. public int findNumGreater(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, all elements right of node are // greater than key, add this to our total and look to the left else if (key.compareTo(node.key) < 0) { return 1 + node.numRight + findNumGreater(node.left, key); } // If key is greater than node.key, then look to the right as // all elements to the left of node are smaller than key else { return findNumGreater(node.right, key); } }// end findNumGreater(RedBlackNode, int key) /** * Returns sorted list of keys greater than key. Size of list will not * exceed maxReturned * * @param key Key to search for * @param maxReturned Maximum number of results to return * @return List of keys greater than key. List may not exceed * maxReturned */ public List<T> getGreaterThan(T key, Integer maxReturned) { List<T> list = new ArrayList<T>(); getGreaterThan(root, key, list); return list.subList(0, Math.min(maxReturned, list.size())); } private void getGreaterThan(RedBlackNode<T> node, T key, List<T> list) { if (isNil(node)) { return; } else if (node.key.compareTo(key) > 0) { getGreaterThan(node.left, key, list); list.add(node.key); getGreaterThan(node.right, key, list); } else { getGreaterThan(node.right, key, list); } } // @param: node, the root of the tree, the key who we must compare other // node key's to. // @return: the number of nodes smaller than key. public int findNumSmaller(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, look to the left as all // elements on the right of node are greater than key else if (key.compareTo(node.key) <= 0) { return findNumSmaller(node.left, key); } // If key is larger than node.key, all elements to the left of // node are smaller than key, add this to our total and look // to the right. else { return 1 + node.numLeft + findNumSmaller(node.right, key); } }// end findNumSmaller(RedBlackNode nod, int key) // @param: node, the RedBlackNode we must check to see whether it's nil // @return: return's true of node is nil and false otherwise private boolean isNil(RedBlackNode node) { // return appropriate value return node == nil; }// end isNil(RedBlackNode node) // @return: return's the size of the tree // Return's the # of nodes including the root which the RedBlackTree // rooted at root has. public int size() { // Return the number of nodes to the root's left + the number of // nodes on the root's right + the root itself. return root.numLeft + root.numRight + 1; }// end size() }// end class RedBlackTree }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
2d417183c3eab839f8686f76b395f3e8
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int w = sc.nextInt(); while (w-- > 0) { int n = sc.nextInt(); long index = 0; int[] arr = new int[n]; long[] ca = new long[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); for (int i = 0; i < n; i++) { long t = 0; for (int j = 0; j < i; j++) { if (arr[j] > arr[i]) { index += ca[j]; } ca[j] += t; if (arr[j] < arr[i]) { t++; } } } sb.append(index).append("\n"); } sc.close(); System.out.println(sb); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9f37cb8c1e9d3591757136275ee4d601
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class Main { static int N = 5010; static int[][] minl,minr; static int[] tr1,tr2; static int n; static int lowbit(int x){ return x&-x; } static void add(int[] tr,int x,int v){ for(int i=x;i<=n;i+=lowbit(i))tr[i]+=v; } static int sum(int[] tr,int x){ int ans = 0; for(int i=x;i>0;i-=lowbit(i))ans+=tr[i]; return ans; } public static void main(String[] args) { InputReader s = new InputReader(System.in); //Scanner s = new Scanner(System.in); PrintWriter w = new PrintWriter(System.out); int T = s.nextInt(); while (T-->0){ n = s.nextInt(); int[] a = new int[n+1]; for(int i=1;i<=n;i++)a[i]=s.nextInt(); tr1 = new int[n+1]; tr2 = new int[n+1]; minl = new int[n+1][n+1]; minr = new int[n+1][n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) { minl[i][j] = sum(tr1, j - 1); } add(tr1, a[i], 1); } for(int i=n;i>=1;i--){ for(int j=1;j<=n;j++) { minr[i][j] = sum(tr2, j - 1); } add(tr2, a[i], 1); } long ans = 0; for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ ans+=minr[j][a[i]]*minl[i][a[j]]; } } w.println(ans); } w.flush(); } static class InputReader { private final static int BUF_SZ = 65536; BufferedReader in; StringTokenizer tokenizer; public InputReader(InputStream in) { super(); this.in = new BufferedReader(new InputStreamReader(in), BUF_SZ); tokenizer = new StringTokenizer(""); } private String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
d3eb12a10260bb4ad121630ae299488b
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { int n = sc.ni(); int[] arr = sc.na(n); int[][] hash = new int[n][n]; for(int i = 0; i < n-1; i++) { int[] chash = new int[n]; if(arr[i] > arr[n-1]) chash[n-1] = 1; else chash[n-1] = 0; for(int j = n-2; j > i; j--) { chash[j] = chash[j+1]; if(arr[i] > arr[j]) chash[j]++; } hash[i] = chash; } int[][] secondPair = new int[n][n]; for(int i = n-2; i >= 0; i--) { int[] chash = new int[n]; for(int j = i-1; j >= 0; j--) { chash[j] = chash[j+1]; chash[j] += hash[j][i+1]; } secondPair[i] = chash; } long ans = 0; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(arr[i] < arr[j]) { ans += secondPair[j][i+1]; } } } w.p(ans); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
de6442a2f633fa0e6cb47a8aae581b57
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** //i dont know if it's my luck or am i becoming stupid with time //but i am really disappointed in myself //but one thing i know for sure is i am improving everyday and soon i will certainly get it. public class C_Tokitsukaze_and_Strange_Inequality{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); int array[]= new int[n]; for(int i=0;i<n;i++){ array[i]=s.nextInt(); } int small[][]= new int[n][n]; for(int i=0;i<n;i++){ int num=array[i]; int count=0; for(int j=i+1;j<n;j++){ if(array[j]<num){ count++; } small[i][j]=count; } } // { // //printing // for(int i=0;i<n;i++){ // for(int j=0;j<n;j++){ // System.out.print(small[i][j]+" "); // } // System.out.println(); // } // } // System.out.println("disappointed"); int dp1[][]= new int[n][n]; for(int i=0;i<n;i++){ //i=>last till column int sum=0; for(int j=0;j<=i;j++){ sum+=small[j][i]; } for(int j=0;j<=i;j++){ dp1[j][i]=sum; sum-=small[j][i]; } } // { // //printing // for(int i=0;i<n;i++){ // for(int j=0;j<n;j++){ // System.out.print(dp1[i][j]+" "); // } // System.out.println(); // } // } small= new int[1][1]; int dp2[][]= new int[n][n]; for(int i=0;i<n;i++){ // int hh=0; int hh2=dp1[i][n-1]; for(int j=i;j<n;j++){ // hh+=small[j][n-1]; // dp2[i][j]=hh; if(j+1!=n){ int hh3=hh2-dp1[j+1][n-1]; dp2[i][j]=hh3; } else{ dp2[i][j]=hh2; } } } long ans=0; for(int i=0;i<n;i++){ int num1=array[i]; for(int j=i+1;j<n;j++){ int num2=array[j]; if(num2>num1){ int alpha=dp2[i+1][j-1]; int beta=dp1[i+1][j]; int hh=alpha-beta; ans+=hh; } } } res.append(ans+" \n"); p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
3b169a05d9c5cbc91a3caac0030f61ff
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); class pair { int F, S; pair(int f, int s) { F = f; S = s; } } // ---------------------- solve -------------------------- long q=0; void solve() { int t=1; t = ni(); // comment for no test cases // long start = System.currentTimeMillis(); while(t-- > 0) { //TODO: int n= ni(); int[] a= new int[n+1]; int[][] x= new int[n+1][n+1]; int[][] y= new int[n+1][n+1]; for(int i=1; i<=n; i++){ a[i]=ni(); } for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { y[i][j] = x[i][j] = 0; } } long a1=0; for(int i=1; i<=n; i++) { int b = 0; for(int j=i+1; j<=n; j++) { if(a[j] < a[i]) b++; x[i][j] = b; } a1 += b; } for(int j=1; j<=n; j++){ int b = 0; for(int i=j; i>=1; i--){ b += x[i][j]; y[i][j] = b; } } long q=0, b; for(int i=1; i<=n-3; i++){ long c = x[i][n]; a1-= c; for(int j=i+2; j<n; j++){ if(a[i] < a[j]){ b = a1; c = y[i+1][j]; b -= c; c = x[j][n]; b -= c; c = y[j+1][n]; b -= c; q += b; } } } out.println(q); } // long end = System.currentTimeMillis(); // float sec = 1f*(end - start)/1000f; System.out.println(sec + "seconds"); } // -------- I/O Template ------------- public long pow(long A, long B, long C) { if(A==0) return 0; if(B==0) return 1; long n=pow(A, B/2, C); if(B%2==0){ return (long)((n*n)%C + C )%C; } else{ return (long)(((n*n)%C * A)%C +C)%C; } } char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); return a; } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); if(ip == null || !ip.hasMoreTokens()) ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { try { if (System.getProperty("ONLINE_JUDGE") == null) { br = new BufferedReader(new FileReader("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/input.txt")); out = new PrintWriter("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/output.txt"); } else { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } catch (FileNotFoundException e) { System.out.println(e); } solve(); out.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
14ae22ee69d3a4083839a3d5452feea5
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 1e9 + 7; static long inf = (long) 1e16; static int n, m; static ArrayList<Integer>[] ad, ad1; static int[][] remove, add; static long[] inv, f, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static boolean[] msks; static int[] lazy[], lazyCount; static int[] c, w; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] a = sc.nextArrInt(n); int[][] ad = new int[n][]; int[] deg = new int[n]; // ad1 = new ArrayList[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { deg[i]++; } } } for (int i = 0; i < n; i++) { ad[i] = new int[deg[i]]; for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { ad[i][--deg[i]] = j + 1; } } } FenwickTree ft = new FenwickTree(n + 6); for (int i = 0; i < n; i++) for (int y : ad[i]) ft.point_update(y, 1); long ans = 0; int[] ad1 = new int[n]; for (int i = 0; i < n; i++) { ans -= ft.rsq(i + 1) * 1l * ad1[i]; for (int y : ad[i]) ft.point_update(y, -1); for (int j = i + 1; j < n; j++) { if (a[j] > a[i] && j - i > 1) { ans += ft.rsq(j + 2); ad1[j]++; } } } out.println(ans); } out.flush(); } public static class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n + 1]; } int rsq(int b) // O(log n) { int sum = 0; while (b <= n) { sum += ft[b]; b += b & -b; } // min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a - 1); } void point_update(int k, int val) // O(log n), update = increment { while (k > 0) { ft[k] += val; k -= k & -k; } // min? } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
2712c09e0ddf116209f6116de4988da5
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.*; public class Codeforces { static long mod= 10000_0000_7; public static void main(String[] args) throws Exception { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); // DecimalFormat formatter= new DecimalFormat("#0.000000"); int t=fs.nextInt(); // int t=1; // int n=1000000000; outer:for(int time=1;time<=t;time++) { int n=fs.nextInt(); int arr[]=new int[n+1]; for(int i=1;i<=n;i++) arr[i]=fs.nextInt(); // ST[] st=new ST[n+1]; // st[0]=new ST(0,n); // for(int i=1;i<=n;i++) { // st[i]=st[i-1].pointUpdate(arr[i], 1); // } int st[]=new int[n+1]; // ST[] rst=new ST[n+2]; // rst[n+1]=new ST(0,n); // for(int i=n;i>=1;i--) { // rst[i]=rst[i+1].pointUpdate(arr[i], 1); // } long cnt[][]=new long[n+1][n+1]; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cnt[i][j]= st[j-1]; } for(int j=arr[i];j<=n;j++) st[j]++; } long ans=0; for(int b=2;b<n-1;b++) { for(int c=b+1;c<n;c++) { long ass= cnt[b][arr[c]]; long dss= arr[b]-1-cnt[c+1][arr[b]]; ans+= ass*dss; } } out.println(ans); } out.close(); } static class ST { int leftmost, rightmost; ST lChild, rChild; int max, toProp; long sum; public ST(int leftmost, int rightmost) { // we can also pass a array here and if leftmost==rightmost // we will do sum=arr[leftmost] else same in if case; this.leftmost=leftmost; this.rightmost=rightmost; if (leftmost!=rightmost) { int mid=(leftmost+rightmost)/2; lChild=new ST(leftmost, mid); rChild=new ST(mid+1, rightmost); recalc(); } } int max() { return max+toProp; } long sum() { return sum+toProp; } void recalc() { if (leftmost==rightmost) return; max=Math.max(lChild.max(), rChild.max()); sum=lChild.sum()+rChild.sum(); } void prop() { if (leftmost!=rightmost) { lChild.toProp+=toProp; rChild.toProp+=toProp; toProp=0; } recalc(); } void rangeAdd(int l, int r, int d) { if (l>rightmost || r<leftmost) return; if (l<=leftmost && r>=rightmost) { toProp+=d; return; } prop(); lChild.rangeAdd(l, r, d); rChild.rangeAdd(l, r, d); recalc(); } int max(int l, int r) { if (l>rightmost || r<leftmost) return Integer.MIN_VALUE; if (l<=leftmost && r>=rightmost) { return max(); } prop(); return Math.max(lChild.max(l, r), rChild.max(l, r)); } void pointUpdate(int index,int val) { if(leftmost==rightmost) { sum++; return; } int mid=(leftmost+rightmost)/2; if(index<=mid) lChild.pointUpdate(index,val); else rChild.pointUpdate(index,val); recalc(); } long rangeSum(int l,int r) { if(l>rightmost||r<leftmost) return 0; if(l<=leftmost&&r>=rightmost) return sum; prop(); return lChild.rangeSum(l, r)+rChild.rangeSum(l, r); } } static long pow(long a,long b) { if(b<0) return 1; long res=1; while(b!=0) { if((b&1)!=0) { res*=a; res%=mod; } a*=a; a%=mod; b=b>>1; } return res; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long nck(int n,int k) { if(k>n) return 0; long res=1; res*=fact(n); res%=mod; res*=modInv(fact(k)); res%=mod; res*=modInv(fact(n-k)); res%=mod; return res; } static long fact(long n) { // return fact[(int)n]; long res=1; for(int i=2;i<=n;i++) { res*=i; res%=mod; } return res; } static long modInv(long n) { return pow(n,mod-2); } static void sort(int[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } static void sort(long[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); long temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { String str=""; try { str= (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readArrayL(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b5fcb5744afa8db5d5ab5a634b12fcb3
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.util.*; public class Main { private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); private StringTokenizer st; private final Long MOD = 1000000007L; private final String endl = "\n"; private final String space = " "; boolean isConsonantUpperCase(char c) { return !isVowelUpperCase(c); } // only for upper case boolean isVowelUpperCase(char c) { c = (c + "").toUpperCase().charAt(0); return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } // IO UTILS void log(Object... args) { if (!TESTING) return; for (Object s : args) System.out.print(s.toString() + " "); System.out.println(); } String line() throws IOException { return in.readLine().trim(); } StringTokenizer tokens() throws IOException { return new StringTokenizer(line()); } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(line()); return st.nextToken(); } long l(String s) { return Long.parseLong(s); } long rl() throws IOException { return l(nextToken()); } long[] rla(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = rl(); return arr; } int i(String s) { return Integer.parseInt(s); } int ri() throws IOException { return i(nextToken()); } int[] ria(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = ri(); return arr; } String rs() throws IOException { return nextToken(); } String[] rsa(int n) throws IOException { String[] s = new String[n]; for (int i = 0; i < n; i++) s[i] = nextToken(); return s; } double d(String s) { return Double.parseDouble(s); } double rd() throws IOException { return d(nextToken()); } double[] rda(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = rd(); } return arr; } void ol(Object... arg) throws IOException { int n = arg.length; for (int i = 0; i < n - 1; i += 1) { os(arg[i].toString()); } if (n > 0) ol(arg[n - 1].toString()); } void ol() throws IOException { out.write(endl); } void os() throws IOException { out.write(space); } void ol(String s) throws IOException { out.write(s + endl); } void os(String s) throws IOException { out.write(s + space); } void ol(int n) throws IOException { out.write(n + endl); } void os(int s) throws IOException { out.write(s + space); } void ol(long s) throws IOException { out.write(s + endl); } void os(long s) throws IOException { out.write(s + space); } void o(String s) throws IOException { out.write(s); } void o(int n) throws IOException { out.write(n + ""); } void o(long s) throws IOException { out.write(s + ""); } // IO UTILS END // MATH UTILS long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } long lcm(long a, long b) { long g = gcd(a, b); return (a / g) * b; // directly multiply a and b can overflow } public long modInv(long a, long MOD) { return new BigInteger(a + "").modPow(new BigInteger((MOD - 2) + ""), new BigInteger(MOD + "")).longValue(); } public long modPro(long a, long b, long MOD) { return ((a % MOD) * (b % MOD)) % MOD; } private long factorialMod(int n, long MOD) { long pro = 1; for (long i = 1; i <= n; i++) { pro = pro * i; pro %= MOD; } return pro; } static void ruffleSort(int[] a) { // ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { // ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } boolean[] sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 4; i <= n; i += 2) { prime[i] = false; } for (int p = 3; p * p <= n; p += 2) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } return prime; } // MATH UTILS END private final boolean TESTING = false; public static void main(String[] args) throws Exception { new Main().solve(); } private void solve() throws Exception { int testCases = 1; testCases = Integer.parseInt(in.readLine().trim()); preProcess(); for (int i = 1; i <= testCases; i++) { solveTestCase(i); } out.flush(); out.close(); } void preProcess() { } // make debugging flag based private void solveTestCase(int testCaseNumber) throws Exception { int n = ri(); int arr[] = ria(n); int max = 5001; // max = 11; int less[][] = new int[n][max]; for (int i = 0; i < n; i += 1) { int curr = arr[i]; for (int j = 0; j < max; j += 1) { if (curr < j) less[i][j] = 1; } } for (int i = 1; i < n; i += 1) { for (int j = 0; j < max; j += 1) { less[i][j] += less[i - 1][j]; } } // for (int[] ints : less) { // ol(Arrays.toString(ints)); // } // ol(); int more[][] = new int[n][max]; for (int i = n - 1; i >= 0; i -= 1) { int curr = arr[i]; for (int j = 0; j < max; j += 1) { if (curr < j) more[i][j] = 1; } } // for (int[] ints : more) { // ol(Arrays.toString(ints)); // } // ol(); for (int i = n - 2; i >= 0; i -= 1) { for (int j = 0; j < max; j += 1) { more[i][j] += more[i + 1][j]; } } // for (int[] ints : more) { // ol(Arrays.toString(ints)); // } long ans = 0; for (int b = 1; b < n; b += 1) { for (int c = b + 1; c < n - 1; c += 1) { ans += less[b - 1][arr[c]] * more[c + 1][arr[b]]; // ol(b,c,ans); } } ol(ans); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
7bc7b76d843971f1ab59a673784e4170
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.io.ByteArrayOutputStream; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.util.InputMismatchException; import java.io.FileNotFoundException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author tauros */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; RealFastReader in = new RealFastReader(inputStream); RealFastWriter out = new RealFastWriter(outputStream); CF789C solver = new CF789C(); solver.solve(1, in, out); out.close(); } static class CF789C { public void solve(int testNumber, RealFastReader in, RealFastWriter out) { int cases = in.ni(); int[][] preSum = new int[5001][5001]; while (cases-- > 0) { int n = in.ni(); int[] nums = new int[n]; for (int i = 1; i <= n; i++) { Arrays.fill(preSum[i], 1, n + 1, 0); } for (int i = 1; i <= n; i++) { nums[i - 1] = in.ni(); for (int j = i; j <= n; j++) { preSum[j][nums[i - 1]]++; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { preSum[i][j] += preSum[i][j - 1]; } } long ans = 0; for (int b = 1; b <= n; b++) { for (int c = b + 1; c <= n; c++) { int aCnt = preSum[b - 1][nums[c - 1] - 1]; int dCnt = preSum[n][nums[b - 1] - 1] - preSum[c][nums[b - 1] - 1]; ans += 1l * aCnt * dCnt; } } out.println(ans); } out.flush(); } } static class RealFastReader { InputStream is; private byte[] inbuf = new byte[1024]; public int lenbuf = 0; public int ptrbuf = 0; public RealFastReader(final InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) { throw new InputMismatchException(); } if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) { return -1; } } return inbuf[ptrbuf++]; } public int ni() { return (int) nl(); } public long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } static class RealFastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private OutputStream out; private Writer writer; private int ptr = 0; private RealFastWriter() { out = null; } public RealFastWriter(Writer writer) { this.writer = new BufferedWriter(writer); out = new ByteArrayOutputStream(); } public RealFastWriter(OutputStream os) { this.out = os; } public RealFastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public RealFastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) { innerflush(); } return this; } public RealFastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) { innerflush(); } }); return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) { return 19; } if (l >= 100000000000000000L) { return 18; } if (l >= 10000000000000000L) { return 17; } if (l >= 1000000000000000L) { return 16; } if (l >= 100000000000000L) { return 15; } if (l >= 10000000000000L) { return 14; } if (l >= 1000000000000L) { return 13; } if (l >= 100000000000L) { return 12; } if (l >= 10000000000L) { return 11; } if (l >= 1000000000L) { return 10; } if (l >= 100000000L) { return 9; } if (l >= 10000000L) { return 8; } if (l >= 1000000L) { return 7; } if (l >= 100000L) { return 6; } if (l >= 10000L) { return 5; } if (l >= 1000L) { return 4; } if (l >= 100L) { return 3; } if (l >= 10L) { return 2; } return 1; } public RealFastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) { innerflush(); } if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public RealFastWriter writeln(long x) { return write(x).writeln(); } public RealFastWriter writeln() { return write((byte) '\n'); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { if (writer != null) { writer.write(((ByteArrayOutputStream) out).toString()); out = new ByteArrayOutputStream(); writer.flush(); } else { out.flush(); } } catch (IOException e) { throw new RuntimeException("flush"); } } public RealFastWriter println(long x) { return writeln(x); } public void close() { flush(); try { out.close(); } catch (Exception e) { } } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
34913754be20a022a4c1e09ca9d46fe2
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.stream.IntStream; import java.io.ByteArrayOutputStream; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.util.InputMismatchException; import java.io.FileNotFoundException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author tauros */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; RealFastReader in = new RealFastReader(inputStream); RealFastWriter out = new RealFastWriter(outputStream); CF789C solver = new CF789C(); solver.solve(1, in, out); out.close(); } static class CF789C { public void solve(int testNumber, RealFastReader in, RealFastWriter out) { int cases = in.ni(); while (cases-- > 0) { int n = in.ni(); int[] nums = in.na(n); int[][] preSum = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { preSum[j][nums[i - 1]]++; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { preSum[i][j] += preSum[i][j - 1]; } } long ans = 0; for (int b = 1; b <= n; b++) { for (int c = b + 1; c <= n; c++) { long aCnt = preSum[b - 1][nums[c - 1] - 1]; long dCnt = preSum[n][nums[b - 1] - 1] - preSum[c][nums[b - 1] - 1]; ans += aCnt * dCnt; } } out.println(ans); } out.flush(); } } static class RealFastReader { InputStream is; private byte[] inbuf = new byte[1024]; public int lenbuf = 0; public int ptrbuf = 0; public RealFastReader(final InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) { throw new InputMismatchException(); } if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) { return -1; } } return inbuf[ptrbuf++]; } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int ni() { return (int) nl(); } public long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } static class RealFastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private OutputStream out; private Writer writer; private int ptr = 0; private RealFastWriter() { out = null; } public RealFastWriter(Writer writer) { this.writer = new BufferedWriter(writer); out = new ByteArrayOutputStream(); } public RealFastWriter(OutputStream os) { this.out = os; } public RealFastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public RealFastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) { innerflush(); } return this; } public RealFastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) { innerflush(); } }); return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) { return 19; } if (l >= 100000000000000000L) { return 18; } if (l >= 10000000000000000L) { return 17; } if (l >= 1000000000000000L) { return 16; } if (l >= 100000000000000L) { return 15; } if (l >= 10000000000000L) { return 14; } if (l >= 1000000000000L) { return 13; } if (l >= 100000000000L) { return 12; } if (l >= 10000000000L) { return 11; } if (l >= 1000000000L) { return 10; } if (l >= 100000000L) { return 9; } if (l >= 10000000L) { return 8; } if (l >= 1000000L) { return 7; } if (l >= 100000L) { return 6; } if (l >= 10000L) { return 5; } if (l >= 1000L) { return 4; } if (l >= 100L) { return 3; } if (l >= 10L) { return 2; } return 1; } public RealFastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) { innerflush(); } if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public RealFastWriter writeln(long x) { return write(x).writeln(); } public RealFastWriter writeln() { return write((byte) '\n'); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { if (writer != null) { writer.write(((ByteArrayOutputStream) out).toString()); out = new ByteArrayOutputStream(); writer.flush(); } else { out.flush(); } } catch (IOException e) { throw new RuntimeException("flush"); } } public RealFastWriter println(long x) { return writeln(x); } public void close() { flush(); try { out.close(); } catch (Exception e) { } } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
a3fe25d96b83728d7933dccc4c6883f9
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class C { public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); a:while(t-->0) { int n=sc.nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } long ans=0; for(int i=1;i<n-2;i++) { int cntr=0,cntl=0; HashSet<Integer>hs=new HashSet<Integer>(); for(int j=i+1;j<n;j++) { if(a[j]<a[i])cntr++; } for(int j=0;j<i;j++)hs.add(a[j]); int[]pre=new int[n+1]; pre[1]=hs.contains(1)?1:0; for(int j=2;j<=n;j++) { pre[j]=pre[j-1]; if(hs.contains(j))pre[j]++; } for(int j=i+1;j<n;j++) { cntl=pre[a[j]]; if(a[j]<a[i])cntr--; ans+=1l*cntl*cntr; } } out.println(ans); } out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } static class SegmentTree { int[]arr,seg,lazy; int N; int UNCALC; public SegmentTree(int[]a) { arr=new int[a.length]; for(int i=0;i<a.length;i++) { arr[i]=a[i]; } N=a.length-1; seg=new int[N<<1]; lazy=new int[N<<1]; build(1,1,N); } public void build(int node,int l,int r) { if(l==r) {seg[node]=arr[l];return;} int mid=(l+r)/2; build(node<<1,l,mid); build(node<<1|1,mid+1,r); seg[node]=calc(seg[node<<1],seg[node<<1|1]); } private int calc(int i, int j) { return i+j; } public int query(int i,int j) { return query(1,1,N,i,j); } public int query(int node,int l,int r,int i,int j) {//quering on i and j if(l>j||r<i)return UNCALC; if(r<=j&&l>=i)return seg[node]; int mid=l+r>>1; propagate(node, l, r); int left=query(node<<1,l,mid,i,j); int right=query(node<<1|1,mid+1,r,i,j); return calc(left,right); } public void updatePoint(int idx,int val) { int node=idx+N-1; arr[idx]+=val; seg[node]+=val; node>>=1; while(node>0) { seg[node]=seg[node<<1]+seg[node<<1|1]; node>>=1; } } void updateRange(int i,int j,int val) { updateRange(1, 1, N, i, j, val); } void updateRange(int node,int l,int r,int i,int j,int val) { if(l>j||r<i)return ; if(l>=i&&r<=j) { seg[node]+=(r-l+1)*val; lazy[node]+=val;return; } int le=node<<1; int ri=node<<1|1,mid=l+r>>1; propagate(node, l, r); updateRange(le, l, mid, i, j, val); updateRange(ri, mid+1, r, i, j, val); seg[node]=seg[le]+seg[ri]; } void propagate(int node,int le,int ri) { int l=node<<1; int r=node<<1|1,mid=le+ri>>1; lazy[l]+=lazy[node]; lazy[r]+=lazy[node]; seg[l]+=lazy[node]*(mid-le+1); seg[r]+=lazy[node]*(ri-mid); lazy[node]=0; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
f082a80ad6fd246d7bd0ed8462a0569e
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/* Challenge 1: Newbie to CM in 1year (Dec 2021 - Nov 2022) 5* Codechef Challenge 2: CM to IM in 1 year (Dec 2022 - Nov 2023) 6* Codechef Challenge 3: IM to GM in 1 year (Dec 2023 - Nov 2024) 7* Codechef Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do */ import java.util.*; import java.io.*; import java.math.*; public class C { static StringBuffer str=new StringBuffer(); static int n; static int a[]; // i < j < k < l // i<k j<l // a[i]<a[k] and a[j]>a[l] static long solve(){ int p1[][]=new int[n+1][n+1]; for(int i=0;i<n;i++){ for(int k=i+1;k<n;k++){ if(a[i]<a[k]) p1[i][k]++; } } int p2[][]=new int[n+1][n+1]; for(int j=0;j<n;j++){ for(int l=j+1;l<n;l++){ if(a[j]>a[l]) p2[j][l]++; } } for(int j=n-1;j>=0;j--){ for(int l=n-1;l>=0;l--){ p2[j][l]+=p2[j+1][l]; } } for(int i=0;i<=n;i++){ for(int j=n-1;j>=0;j--){ p2[i][j]+=p2[i][j+1]; } } long ans=0; for(int i=n-1;i>=0;i--){ for(int k=i+1;k<n;k++){ ans+=p1[i][k]*(p2[i+1][k+1]-p2[k][k+1]); } } return ans; } public static void main(String[] args) throws java.lang.Exception { BufferedReader bf; PrintWriter pw; boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } int t = Integer.parseInt(bf.readLine().trim()); while (t-- > 0) { n=Integer.parseInt(bf.readLine().trim()); a=new int[n]; String s[]=bf.readLine().trim().split("\\s+"); for(int i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); str.append(solve()).append("\n"); } pw.println(str); pw.flush(); // System.outin.print(str); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
19e66dffb44e2ec33fde27e6e0c95458
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int T=sc.nextInt(); while(T-->0) { int n=sc.nextInt(); int[] a=new int[n+1]; for(int i=1;i<=n;i++) a[i]=sc.nextInt(); /* a[c]>a[a] 1<=i<=b-1 a[b]>a[d] c+1<=i<=n */ long[][] dp=new long[n+1][n+1]; // dp[i][j] 前i个数中小于等于j的数字个数 for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) dp[i][j]=dp[i-1][j]; for(int j=a[i]+1;j<=n;j++) dp[i][j]++; } long ans=0; for(int b=1;b<=n;b++) { for(int c=b+1;c<=n;c++) ans+=dp[b-1][a[c]]*(dp[n][a[b]]-dp[c][a[b]]); } System.out.println(ans); } sc.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b2e3f1f8eba62e5d8779c9a04765d14e
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int T=sc.nextInt(); while(T-->0) { int n=sc.nextInt(); int[] a=new int[n+1]; for(int i=1;i<=n;i++) a[i]=sc.nextInt(); long[][] dp=new long[n+1][n+1]; // dp[i][j] 前i个数中小于等于j的数字个数 for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) dp[i][j]=dp[i-1][j]; for(int j=a[i];j<=n;j++) dp[i][j]++; } long ans=0; for(int b=1;b<=n;b++) { for(int c=b+1;c<=n;c++) ans+=dp[b-1][a[c]-1]*(dp[n][a[b]]-dp[c][a[b]]); } System.out.println(ans); } sc.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
0d4fea1a0d7fa9065715ebd2bd248cb7
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C_Tokitsukaze_and_Strange_Inequality { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans = new StringBuilder(); static int testCases, n, iterations; static long tab[]; static void solve(int t) { long dp[][] = new long[n][n]; for(int i = 0; i < n; ++i) { for(int j = 0; j < i; ++j) { int adder = 0; if(tab[j] < tab[i]) { adder = 1; } if(j - 1 >= 0) { dp[i][j] = dp[i][j - 1] + adder; } else { dp[i][j] = adder; } } for(int j = n - 1; j > i; --j) { int adder = 0; if(tab[j] < tab[i]) { adder = 1; } if(j + 1 < n) { dp[i][j] = dp[i][j + 1] + adder; } else { dp[i][j] = adder; } } } long result = 0; for(int i = 1; i < n - 2; ++i) { for(int j = i + 1; j < n - 1; ++j) { long left = dp[j][i - 1]; long right = dp[i][j + 1]; result += left * right; } } ans.append(result); if (t != testCases) { ans.append("\n"); } } public static void main(String[] amit) throws IOException { testCases = in.nextInt(); for (int t = 0; t < testCases; ++t) { n = in.nextInt(); tab = new long[n]; for (int i = 0; i < n; ++i) { tab[i] = in.nextLong(); } solve(t + 1); } out.print(ans.toString()); out.flush(); in.close(); } static boolean isSmaller(String str1, String str2) { int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) { return true; } if (n2 < n1) { return false; } for (int i = 0; i < n1; i++) { if (str1.charAt(i) < str2.charAt(i)) { return true; } else if (str1.charAt(i) > str2.charAt(i)) { return false; } } return false; } static String sub(String str1, String str2) { if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n1 - n2; int carry = 0; for (int i = n2 - 1; i >= 0; i--) { int sub = (((int) str1.charAt(i + diff) - (int) '0') - ((int) str2.charAt(i) - (int) '0') - carry); if (sub < 0) { sub = sub + 10; carry = 1; } else { carry = 0; } str += String.valueOf(sub); } for (int i = n1 - n2 - 1; i >= 0; i--) { if (str1.charAt(i) == '0' && carry > 0) { str += "9"; continue; } int sub = (((int) str1.charAt(i) - (int) '0') - carry); if (i > 0 || sub > 0) { str += String.valueOf(sub); } carry = 0; } return new StringBuilder(str).reverse().toString(); } static String sum(String str1, String str2) { if (str1.length() > str2.length()) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; int carry = 0; for (int i = n1 - 1; i >= 0; i--) { int sum = ((int) (str1.charAt(i) - '0') + (int) (str2.charAt(i + diff) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int) (str2.charAt(i) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } if (carry > 0) { str += (char) (carry + '0'); } return new StringBuilder(str).reverse().toString(); } static long detect_sum(int i, long a[], long sum) { if (i >= a.length) { return sum; } return detect_sum(i + 1, a, sum + a[i]); } static String mul(String num1, String num2) { int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) { return "0"; } int result[] = new int[len1 + len2]; int i_n1 = 0; int i_n2 = 0; for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; i_n2 = 0; for (int j = len2 - 1; j >= 0; j--) { int n2 = num2.charAt(j) - '0'; int sum = n1 * n2 + result[i_n1 + i_n2] + carry; carry = sum / 10; result[i_n1 + i_n2] = sum % 10; i_n2++; } if (carry > 0) { result[i_n1 + i_n2] += carry; } i_n1++; } int i = result.length - 1; while (i >= 0 && result[i] == 0) { i--; } if (i == -1) { return "0"; } String s = ""; while (i >= 0) { s += (result[i--]); } return s; } static class Node<T> { T data; Node<T> next; public Node() { this.next = null; } public Node(T data) { this.data = data; this.next = null; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } @Override public String toString() { return this.getData().toString() + " "; } } static class ArrayList<T> { Node<T> head, tail; int len; public ArrayList() { this.head = null; this.tail = null; this.len = 0; } int size() { return len; } boolean isEmpty() { return len == 0; } int indexOf(T data) { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; int index = -1, i = 0; while (temp != null) { if (temp.getData() == data) { index = i; } i++; temp = temp.getNext(); } return index; } void add(T data) { Node<T> newNode = new Node<>(data); if (isEmpty()) { head = newNode; tail = newNode; len++; } else { tail.setNext(newNode); tail = newNode; len++; } } void see() { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; while (temp != null) { out.print(temp.getData().toString() + " "); out.flush(); temp = temp.getNext(); } out.println(); out.flush(); } void inserFirst(T data) { Node<T> newNode = new Node<>(data); Node<T> temp = head; if (isEmpty()) { head = newNode; tail = newNode; len++; } else { newNode.setNext(temp); head = newNode; len++; } } T get(int index) { if (isEmpty() || index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { return head.getData(); } Node<T> temp = head; int i = 0; T data = null; while (temp != null) { if (i == index) { data = temp.getData(); } i++; temp = temp.getNext(); } return data; } void addAt(T data, int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } Node<T> newNode = new Node<>(data); int i = 0; Node<T> temp = head; while (temp.next != null) { if (i == index) { newNode.setNext(temp.next); temp.next = newNode; } i++; temp = temp.getNext(); } // temp.setNext(temp); len++; } void popFront() { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } if (head == tail) { head = null; tail = null; } else { head = head.getNext(); } len--; } void removeAt(int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { this.popFront(); return; } Node<T> temp = head; int i = 0; Node<T> n = new Node<>(); while (temp != null) { if (i == index) { n.next = temp.next; temp.next = n; break; } i++; n = temp; temp = temp.getNext(); } tail = n; --len; } void clearAll() { this.head = null; this.tail = null; } } static void merge(long a[], int left, int right, int mid) { int n1 = mid - left + 1, n2 = right - mid; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; i++) { L[i] = a[left + i]; } for (int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; } int i = 0, j = 0, k1 = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { a[k1] = L[i]; i++; } else { a[k1] = R[j]; j++; } k1++; } while (i < n1) { a[k1] = L[i]; i++; k1++; } while (j < n2) { a[k1] = R[j]; j++; k1++; } } static void sort(long a[], int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; sort(a, left, mid); sort(a, mid + 1, right); merge(a, left, right, mid); } static class Scanner { BufferedReader in; StringTokenizer st; public Scanner() { in = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } String nextLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void close() throws IOException { in.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
07041772e232ba0aa03d3634a912acf7
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C_Tokitsukaze_and_Strange_Inequality { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans = new StringBuilder(); static int testCases, n, iterations; static long tab[]; static void solve(int t) { long dp[][] = new long[n][n]; for(int i = 0; i < n; ++i) { for(int j = 0; j < i; ++j) { int adder = 0; if(tab[j] < tab[i]) { adder = 1; } if(j - 1 >= 0) { dp[i][j] = dp[i][j - 1] + adder; } else { dp[i][j] = adder; } } for(int j = n - 1; j > i; --j) { int adder = 0; if(tab[j] < tab[i]) { adder = 1; } if(j + 1 < n) { dp[i][j] = dp[i][j + 1] + adder; } else { dp[i][j] = adder; } } } long result = 0; for(int i = 1; i < n - 2; ++i) { for(int j = i + 1; j < n - 1; ++j) { long left = dp[j][i - 1]; long right = dp[i][j + 1]; result += left * right; } } ans.append(result); if (t != testCases) { ans.append("\n"); } } public static void main(String[] amit) throws IOException { testCases = in.nextInt(); for (int t = 0; t < testCases; ++t) { n = in.nextInt(); tab = new long[n]; for (int i = 0; i < n; ++i) { tab[i] = in.nextLong(); } solve(t + 1); } out.print(ans.toString()); out.flush(); in.close(); } static boolean isSmaller(String str1, String str2) { int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) { return true; } if (n2 < n1) { return false; } for (int i = 0; i < n1; i++) { if (str1.charAt(i) < str2.charAt(i)) { return true; } else if (str1.charAt(i) > str2.charAt(i)) { return false; } } return false; } static String sub(String str1, String str2) { if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n1 - n2; int carry = 0; for (int i = n2 - 1; i >= 0; i--) { int sub = (((int) str1.charAt(i + diff) - (int) '0') - ((int) str2.charAt(i) - (int) '0') - carry); if (sub < 0) { sub = sub + 10; carry = 1; } else { carry = 0; } str += String.valueOf(sub); } for (int i = n1 - n2 - 1; i >= 0; i--) { if (str1.charAt(i) == '0' && carry > 0) { str += "9"; continue; } int sub = (((int) str1.charAt(i) - (int) '0') - carry); if (i > 0 || sub > 0) { str += String.valueOf(sub); } carry = 0; } return new StringBuilder(str).reverse().toString(); } static String sum(String str1, String str2) { if (str1.length() > str2.length()) { String t = str1; str1 = str2; str2 = t; } String str = ""; int n1 = str1.length(), n2 = str2.length(); int diff = n2 - n1; int carry = 0; for (int i = n1 - 1; i >= 0; i--) { int sum = ((int) (str1.charAt(i) - '0') + (int) (str2.charAt(i + diff) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } for (int i = n2 - n1 - 1; i >= 0; i--) { int sum = ((int) (str2.charAt(i) - '0') + carry); str += (char) (sum % 10 + '0'); carry = sum / 10; } if (carry > 0) { str += (char) (carry + '0'); } return new StringBuilder(str).reverse().toString(); } static long detect_sum(int i, long a[], long sum) { if (i >= a.length) { return sum; } return detect_sum(i + 1, a, sum + a[i]); } static String mul(String num1, String num2) { int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) { return "0"; } int result[] = new int[len1 + len2]; int i_n1 = 0; int i_n2 = 0; for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; i_n2 = 0; for (int j = len2 - 1; j >= 0; j--) { int n2 = num2.charAt(j) - '0'; int sum = n1 * n2 + result[i_n1 + i_n2] + carry; carry = sum / 10; result[i_n1 + i_n2] = sum % 10; i_n2++; } if (carry > 0) { result[i_n1 + i_n2] += carry; } i_n1++; } int i = result.length - 1; while (i >= 0 && result[i] == 0) { i--; } if (i == -1) { return "0"; } String s = ""; while (i >= 0) { s += (result[i--]); } return s; } static class Node<T> { T data; Node<T> next; public Node() { this.next = null; } public Node(T data) { this.data = data; this.next = null; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } @Override public String toString() { return this.getData().toString() + " "; } } static class ArrayList<T> { Node<T> head, tail; int len; public ArrayList() { this.head = null; this.tail = null; this.len = 0; } int size() { return len; } boolean isEmpty() { return len == 0; } int indexOf(T data) { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; int index = -1, i = 0; while (temp != null) { if (temp.getData() == data) { index = i; } i++; temp = temp.getNext(); } return index; } void add(T data) { Node<T> newNode = new Node<>(data); if (isEmpty()) { head = newNode; tail = newNode; len++; } else { tail.setNext(newNode); tail = newNode; len++; } } void see() { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } Node<T> temp = head; while (temp != null) { out.print(temp.getData().toString() + " "); out.flush(); temp = temp.getNext(); } out.println(); out.flush(); } void inserFirst(T data) { Node<T> newNode = new Node<>(data); Node<T> temp = head; if (isEmpty()) { head = newNode; tail = newNode; len++; } else { newNode.setNext(temp); head = newNode; len++; } } T get(int index) { if (isEmpty() || index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { return head.getData(); } Node<T> temp = head; int i = 0; T data = null; while (temp != null) { if (i == index) { data = temp.getData(); } i++; temp = temp.getNext(); } return data; } void addAt(T data, int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } Node<T> newNode = new Node<>(data); int i = 0; Node<T> temp = head; while (temp.next != null) { if (i == index) { newNode.setNext(temp.next); temp.next = newNode; } i++; temp = temp.getNext(); } // temp.setNext(temp); len++; } void popFront() { if (isEmpty()) { throw new ArrayIndexOutOfBoundsException(); } if (head == tail) { head = null; tail = null; } else { head = head.getNext(); } len--; } void removeAt(int index) { if (index >= len) { throw new ArrayIndexOutOfBoundsException(); } if (index == 0) { this.popFront(); return; } Node<T> temp = head; int i = 0; Node<T> n = new Node<>(); while (temp != null) { if (i == index) { n.next = temp.next; temp.next = n; break; } i++; n = temp; temp = temp.getNext(); } tail = n; --len; } void clearAll() { this.head = null; this.tail = null; } } static void merge(long a[], int left, int right, int mid) { int n1 = mid - left + 1, n2 = right - mid; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; i++) { L[i] = a[left + i]; } for (int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; } int i = 0, j = 0, k1 = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { a[k1] = L[i]; i++; } else { a[k1] = R[j]; j++; } k1++; } while (i < n1) { a[k1] = L[i]; i++; k1++; } while (j < n2) { a[k1] = R[j]; j++; k1++; } } static void sort(long a[], int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; sort(a, left, mid); sort(a, mid + 1, right); merge(a, left, right, mid); } static class Scanner { BufferedReader in; StringTokenizer st; public Scanner() { in = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } String nextLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void close() throws IOException { in.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
f7a289fbf17ed90664a16af3dbe7c597
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class B { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); // static int g[][]; static ArrayList<Integer> g[]; static long mod=(long)998244353,INF=Long.MAX_VALUE; static boolean set[]; static int max=0; static int lca[][]; static int par[],col[],D[]; static long fact[]; static int size[],N; static long dp[][],sum[][],f[]; static int seg[],seg1[],seg2[]; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int T=i(); outer:while(T-->0) { int N=i(); int A[]=input(N); int left[][]=new int[N+5][N+5]; for(int i=0; i<N; i++) { left[i+1][A[i]+1]=1; } for(int i=1; i<=N; i++) { for(int j=1; j<=N; j++) { left[i][j]+=left[i][j-1]; } } for(int j=1; j<=N; j++) { for(int i=1; i<=N; i++) { left[i][j]+=left[i-1][j]; } } // // print(left); long s=0; for(int i=0; i<N; i++) { for(int j=i+1; j<N-1; j++) { int b=A[i],c=A[j]; long x=left[i][c]; long y=left[N][b]-left[j+1][b]; // System.out.println(A[i]+" "+A[j]+" "+x+" "+y+" sum--- "+(x*y)); s+=(x*y); } } ans.append(s+"\n"); } out.print(ans); out.close(); } static void dfs(int n,int p,long A[],HashMap<String,Integer> mp) { for(int c:g[n]) { if(c!=p) { long x=mp.get(n+" "+c); long y=mp.get(c+" "+n); if(A[n]*y!=A[c]*x) { } dfs(c,n,A,mp); } } } static int count(long N) { int cnt=0; long p=1L; while(p<=N) { if((p&N)!=0)cnt++; p<<=1; } return cnt; } static long kadane(long A[]) { long lsum=A[0],gsum=0; gsum=Math.max(gsum, lsum); for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } public static boolean pal(int i) { StringBuilder sb=new StringBuilder(); StringBuilder rev=new StringBuilder(); int p=1; while(p<=i) { if((i&p)!=0) { sb.append("1"); } else sb.append("0"); p<<=1; } rev=new StringBuilder(sb.toString()); rev.reverse(); if(i==8)System.out.println(sb+" "+rev); return (sb.toString()).equals(rev.toString()); } public static void reverse(int i,int j,int A[]) { while(i<j) { int t=A[i]; A[i]=A[j]; A[j]=t; i++; j--; } } public static int ask(int a,int b,int c) { System.out.println("? "+a+" "+b+" "+c); return i(); } static int[] reverse(int A[],int N) { int B[]=new int[N]; for(int i=N-1; i>=0; i--) { B[N-i-1]=A[i]; } return B; } static boolean isPalin(char X[]) { int i=0,j=X.length-1; while(i<=j) { if(X[i]!=X[j])return false; i++; j--; } return true; } static int distance(int a,int b) { int d=D[a]+D[b]; int l=LCA(a,b); l=2*D[l]; return d-l; } static int LCA(int a,int b) { if(D[a]<D[b]) { int t=a; a=b; b=t; } int d=D[a]-D[b]; int p=1; for(int i=0; i>=0 && p<=d; i++) { if((p&d)!=0) { a=lca[a][i]; } p<<=1; } if(a==b)return a; for(int i=max-1; i>=0; i--) { if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i]) { a=lca[a][i]; b=lca[b][i]; } } return lca[a][0]; } static void dfs(int n,int p) { lca[n][0]=p; if(p!=-1)D[n]=D[p]+1; for(int c:g[n]) { if(c!=p) { dfs(c,n); } } } static int[] prefix_function(char X[])//returns pi(i) array { int N=X.length; int pre[]=new int[N]; for(int i=1; i<N; i++) { int j=pre[i-1]; while(j>0 && X[i]!=X[j]) j=pre[j-1]; if(X[i]==X[j])j++; pre[i]=j; } return pre; } // static TreeNode start; // public static void f(TreeNode root,TreeNode p,int r) // { // if(root==null)return; // if(p!=null) // { // root.par=p; // } // if(root.val==r)start=root; // f(root.left,root,r); // f(root.right,root,r); // } // static int right(int A[],int Limit,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<Limit)l=m; else r=m; } return l; } static int left(int A[],int a,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<a)l=m; else r=m; } return l; } static void build1(int v,int tl,int tr,int A[]) { if(tl==tr) { seg1[v]=A[tl]; return; } int tm=(tl+tr)/2; build1(v*2,tl,tm,A); build1(v*2+1,tm+1,tr,A); seg1[v]=seg1[v*2]+seg1[v*2+1]; } static void update1(int v,int tl,int tr,int index) { if(index==tl && index==tr) { seg1[v]++; } else { int tm=(tl+tr)/2; if(index<=tm)update1(v*2,tl,tm,index); else update1(v*2+1,tm+1,tr,index); seg1[v]=seg1[v*2]+seg1[v*2+1]; } } static int ask1(int v,int tl,int tr,int l,int r) { if(l>r)return 0; if(tl==l && r==tr) { return seg1[v]; } int tm=(tl+tr)/2; return ask1(v*2,tl,tm,l,Math.min(tm, r))+ask1(v*2+1,tm+1,tr,Math.max(tm+1, l),r); } static void build2(int v,int tl,int tr,int A[]) { if(tl==tr) { seg2[v]=A[tl]; return; } int tm=(tl+tr)/2; build2(v*2,tl,tm,A); build2(v*2+1,tm+1,tr,A); seg2[v]=seg2[v*2]+seg2[v*2+1]; } static void update2(int v,int tl,int tr,int index) { if(index==tl && tl==tr) { seg2[v]-=1; } else { int tm=(tl+tr)/2; if(index<=tm)update2(v*2,tl,tm,index); else update2(v*2+1,tm+1,tr,index); seg2[v]=seg2[v*2]+seg2[v*2+1]; } } static int ask2(int v,int tl,int tr,int l,int r) { if(l>r)return 0; if(tl==l && r==tr) { return seg2[v]; } int tm=(tl+tr)/2; return ask2(v*2,tl,tm,l,Math.min(tm, r))+ask2(v*2+1,tm+1,tr,Math.max(tm+1, l),r); } static boolean f(long A[],long m,int N) { long B[]=new long[N]; for(int i=0; i<N; i++) { B[i]=A[i]; } for(int i=N-1; i>=0; i--) { if(B[i]<m)return false; if(i>=2) { long extra=Math.min(B[i]-m, A[i]); long x=extra/3L; B[i-2]+=2L*x; B[i-1]+=x; } } return true; } static int f(int l,int r,long A[],long x) { while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)l=m; else r=m; } return r; } static boolean f(long m,long H,long A[],int N) { long s=m; for(int i=0; i<N-1;i++) { s+=Math.min(m, A[i+1]-A[i]); } return s>=H; } static long ask(long l,long r) { System.out.println("? "+l+" "+r); return l(); } static long f(long N,long M) { long s=0; if(N%3==0) { N/=3; s=N*M; } else { long b=N%3; N/=3; N++; s=N*M; N--; long a=N*M; if(M%3==0) { M/=3; a+=(b*M); } else { M/=3; M++; a+=(b*M); } s=Math.min(s, a); } return s; } static int ask(StringBuilder sb,int a) { System.out.println(sb+""+a); return i(); } static void swap(char X[],int i,int j) { char x=X[i]; X[i]=X[j]; X[j]=x; } static int min(int a,int b,int c) { return Math.min(Math.min(a, b), c); } static long and(int i,int j) { System.out.println("and "+i+" "+j); return l(); } static long or(int i,int j) { System.out.println("or "+i+" "+j); return l(); } static int len=0,number=0; static void f(char X[],int i,int num,int l) { if(i==X.length) { if(num==0)return; //update our num if(isPrime(num))return; if(l<len) { len=l; number=num; } return; } int a=X[i]-'0'; f(X,i+1,num*10+a,l+1); f(X,i+1,num,l); } static boolean is_Sorted(int A[]) { int N=A.length; for(int i=1; i<=N; i++)if(A[i-1]!=i)return false; return true; } static boolean f(StringBuilder sb,String Y,String order) { StringBuilder res=new StringBuilder(sb.toString()); HashSet<Character> set=new HashSet<>(); for(char ch:order.toCharArray()) { set.add(ch); for(int i=0; i<sb.length(); i++) { char x=sb.charAt(i); if(set.contains(x))continue; res.append(x); } } String str=res.toString(); return str.equals(Y); } static boolean all_Zero(int f[]) { for(int a:f)if(a!=0)return false; return true; } static long form(int a,int l) { long x=0; while(l-->0) { x*=10; x+=a; } return x; } static int count(String X) { HashSet<Integer> set=new HashSet<>(); for(char x:X.toCharArray())set.add(x-'0'); return set.size(); } static int f(long K) { long l=0,r=K; while(r-l>1) { long m=(l+r)/2; if(m*m<K)l=m; else r=m; } return (int)l; } // static void build(int v,int tl,int tr,long A[]) // { // if(tl==tr) // { // seg[v]=A[tl]; // } // else // { // int tm=(tl+tr)/2; // build(v*2,tl,tm,A); // build(v*2+1,tm+1,tr,A); // seg[v]=Math.min(seg[v*2], seg[v*2+1]); // } // } static int [] sub(int A[],int B[]) { int N=A.length; int f[]=new int[N]; for(int i=N-1; i>=0; i--) { if(B[i]<A[i]) { B[i]+=26; B[i-1]-=1; } f[i]=B[i]-A[i]; } for(int i=0; i<N; i++) { if(f[i]%2!=0)f[i+1]+=26; f[i]/=2; } return f; } static int[] f(int N) { char X[]=in.next().toCharArray(); int A[]=new int[N]; for(int i=0; i<N; i++)A[i]=X[i]-'a'; return A; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { if(par[a]>par[b]) //this means size of a is less than that of b { int t=b; b=a; a=t; } par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } // static void setGraph(int N,int nodes) // { //// size=new int[N+1]; // par=new int[N+1]; // col=new int[N+1]; //// g=new int[N+1][]; // D=new int[N+1]; // int deg[]=new int[N+1]; // int A[][]=new int[nodes][2]; // for(int i=0; i<nodes; i++) // { // int a=i(),b=i(); // A[i][0]=a; // A[i][1]=b; // deg[a]++; // deg[b]++; // } // for(int i=0; i<=N; i++) // { // g[i]=new int[deg[i]]; // deg[i]=0; // } // for(int a[]:A) // { // int x=a[0],y=a[1]; // g[x][deg[x]++]=y; // g[y][deg[y]++]=x; // } // } static long pow(long a,long b) { //long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2L == 0 || N%3L == 0) return false; for (long i=5; i*i<=N; i+=2) if (N%i==0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(boolean A[][]) { for(boolean a[]:A)print(a); } static void print(long A[][]) { for(long a[]:A)print(a); } static void print(int A[][]) { for(int a[]:A)print(a); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
f7e3a8ed82180462e669bc0bfeb2256c
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class A { static FastReader sc=new FastReader(); static long dp[][]; static int mod=998244353;//1000000007; // static int mod=1000000009; static int max; static int bit[]; static long ans; static long seg[]; static long A[]; static HashMap<Integer,Integer> map; static ArrayList<Integer> l=new ArrayList<Integer>(); public static void main(String[] args) { //CHECK FOR N=1 //CHECK FOR N=1 PrintWriter out=new PrintWriter(System.out); //StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); int A[]=input(n); long B[][]=new long[n][n+1]; int C[]=new int[n+1]; for(int i=n-1;i>=0;i--) { C[A[i]]++; for(int j=0;j<=n;j++) { B[i][j]=C[j]; } } for(int i=0;i<n;i++) { B[i]=prefix(B[i]); } long ans=0; for(int i=n-2;i>=0;i--) { long res=0; for(int j=i-2;j>=0;j--) { if(A[j]>A[i]) { res+=B[i+1][A[j+1]-1]; continue; } res+=B[i+1][A[j+1]-1]; ans+=res; } } System.out.println(ans); } out.close(); // System.out.println(sb.toString()); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 } static class Pair implements Comparable<Pair> { int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return -1; else if(this.y<o.y) return 1; else return 0; } } /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } // public int hashCode() // { // final int temp = 14; // int ans = 1; // ans =x*31+y*13; // return ans; // } // // // Equal objects must produce the same // // hash code as long as they are equal // @Override // public boolean equals(Object o) // { // if (this == o) { // return true; // } // if (o == null) { // return false; // } // if (this.getClass() != o.getClass()) { // return false; // } // Pair other = (Pair)o; // if (this.x != other.x || this.y!=other.y) { // return false; // } // return true; // } } //FRENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
6104f694584f56e04b282136e2f97b69
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// package faltu; import java.util.*; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; public class Main { // ***********************MATHS--STARTS************************************************* // private static ArrayList<Long> get_divisor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a; } private static int CntOfFactor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a.size(); } static long[] sieve; static long[] smallestPrime; public static void sieve() { int n=4000000+1; sieve=new long[n]; smallestPrime=new long[n]; sieve[0]=1; sieve[1]=1; for(int i=2;i<n;i++){ sieve[i]=i; smallestPrime[i]=i; } for(int i=2;i*i<n;i++){ if(sieve[i]==i){ for(int j=i*i;j<n;j+=i){ if(sieve[j]==j)sieve[j]=1; if(smallestPrime[j]==j||smallestPrime[j]>i)smallestPrime[j]=i; } } } } static long nCr(long n,long r,long MOD) { computeFact(n, MOD); if(n<r)return 0; if(r==0)return 1; return fact[(int) n]*mod_inv(fact[(int) r],MOD)%MOD*mod_inv(fact[(int) (n-r)],MOD)%MOD; } static long[]fact; static void computeFact(long n,long MOD) { fact=new long[(int)n+1]; fact[0]=1; for(int i=1;i<=n;i++)fact[i]=(fact[i-1]*i%MOD)%MOD; } static long bin_expo(long a,long b,long MOD) { if(b == 0)return 1; long ans = bin_expo(a,b/2,MOD); ans = (ans*ans)%MOD; if(b % 2!=0){ ans = (ans*a)%MOD; } return ans%MOD; } static int ceil(int x, int y) {return (x % y == 0 ? x / y : (x / y + 1));} static long ceil(long x, long y) {return (x % y == 0 ? x / y : (x / y + 1));} static long mod_add(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} static long mod_mul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} static long mod_sub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} static long mod_inv(long n,long p) {return bin_expo(n,p-2,p);} static long gcd(long a, long b){if (a == 0) {return b;}return gcd(b % a, a); } static int gcd(int a, int b){if (a == 0) {return b; }return gcd(b % a, a); } static long lcm(long a,long b){return (a / gcd(a, b)) * b;} static long min(long x,long y) {return Math.min(x, y);}static long max(long x,long y) {return Math.max(x, y);} static int min(int x,int y) {return Math.min(x, y);}static int max(int x,int y) {return Math.max(x, y);} static ArrayList<String>powof2s; static void powof2S() { long i=1; while(i<(long)2e18) { powof2s.add(String.valueOf(i)); i*=2; } } static long power(long a, long b){ a %=MOD;long out = 1; while (b > 0) { if((b&1)!=0)out = out * a % MOD; a = a * a % MOD; b >>= 1; a*=a; } return out; } static boolean coprime(long a, long b){return (gcd(a, b) == 1);} // ****************************MATHS-ENDS***************************************************** // ***********************BINARY-SEARCH STARTS*********************************************** public static int upperBound(long[] arr, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(arr[mid]<=m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(long[] a, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(a[mid]<m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static int upperBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <=k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static long getClosest(long val1, long val2,long target){if (target - val1 >= val2 - target)return val2; else return val1;} static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { long oi=r.nextInt(n), temp=a[i]; a[i]=a[(int)oi]; a[(int)oi]=temp; } Arrays.sort(a); } static void ruffleSort(int[] a){ int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } int ceilIndex(int input[], int T[], int end, int s){ int start = 0; int middle; int len = end; while(start <= end){ middle = (start + end)/2; if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){ return middle+1; }else if(input[T[middle]] < s){ start = middle+1; }else{ end = middle-1; } } return -1; } static int lowerLimitBinarySearch(ArrayList<Long> v,long k) { int n =v.size(); int first = 0,second = n; while(first <second) { int mid = first + (second-first)/2; if(v.get(mid) > k) { second = mid; }else { first = mid+1; } } if(first < n && v.get(first) < k) { first++; } return first; //1 index } public static int searchindex(long arr[], long t){int index = Arrays.binarySearch(arr, t);return (index < 0) ? -1 : index;} public static long[] sort(long[] a) {ArrayList<Long> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} public static int[] sort(int[] a) {ArrayList<Integer> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} // *******************************BINARY-SEARCH ENDS*********************************************** // *********************************GRAPHS-STARTS**************************************************** // *******----SEGMENT TREE IMPLEMENT---***** // -------------START--------------- void buildTree (int[] arr,int[] tree,int start,int end,int treeNode){ if(start==end){ tree[treeNode]=arr[start]; return; } buildTree(arr,tree,start,end,2*treeNode); buildTree(arr,tree,start,end,2*treeNode+1); tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1]; } void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value){ if(start==end){ arr[idx]=value; tree[treeNode]=value; return; } int mid=(start+end)/2; if(idx>mid)updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value); else updateTree(arr,tree,start,mid,2*treeNode,idx,value); tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1]; } long query(int[]arr,int[]tree,int start,int end,int treeNode,int qleft,int qright) { if(start>=qleft&&end<=qright)return tree[treeNode]; if(start>qright||end<qleft)return 0; int mid=(start+end)/2; long valLeft=query(arr,tree,start,mid-1,treeNode*2,qleft,qright); long valRight=query(arr,tree,mid+1,end,treeNode*2+1,qleft,qright); return valLeft+valRight; } // -------------ENDS--------------- //***********************DSU IMPLEMENT START************************* static int parent[]; static int rank[]; static int[]Size; static void makeSet(int n){ parent=new int[n]; rank=new int[n]; Size=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=0; Size[i]=1; } } static void union(int u,int v){ u=findpar(u); v=findpar(v); if(u==v)return; if(rank[u]<rank[v]) { parent[u]=v; Size[v]+=Size[u]; } else if(rank[v]<rank[u]) { parent[v]=u; Size[u]+=Size[v]; } else{ parent[v]=u; rank[u]++; Size[u]+=Size[v]; } } private static int findpar(int node){ if(node==parent[node])return node; return parent[node]=findpar(parent[node]); } // *********************DSU IMPLEMENT ENDS************************* // ****__________PRIMS ALGO______________________**** private static int prim(ArrayList<node>[] adj,int N,int node) { int key[] = new int[N+1]; int parent[] = new int[N+1]; boolean mstSet[] = new boolean[N+1]; for(int i = 0;i<N;i++) { key[i] = 100000000; mstSet[i] = false; } PriorityQueue<node> pq = new PriorityQueue<node>(N, new node()); key[node] = 0; parent[node] = -1; pq.add(new node( node,key[node])); for(int i = 0;i<N-1;i++) { int u = pq.poll().getV(); mstSet[u] = true; for(node it: adj[u]) { if(mstSet[it.getV()] == false && it.getW() < key[it.getV()]) { parent[it.getV()] = u; key[it.getV()] = (int) it.getW(); pq.add(new node(it.getV(), key[it.getV()])); } } } int sum=0; for(int i=1;i<N;i++) { System.out.println(key[i]); sum+=key[i]; } System.out.println(sum); return sum; } // ****____________DIJKSTRAS ALGO___________**** static int[]dist; static int dijkstra(int u,int n,ArrayList<node>adj[]) { long[]path=new long[n]; dist=new int[n]; Arrays.fill(dist,Integer.MAX_VALUE); dist[u]=0; path[0]=1; PriorityQueue<node>pq=new PriorityQueue<node>(new node()); pq.add(new node(u,0)); while(!pq.isEmpty()) { node v=pq.poll(); if(dist[v.getV()]<v.getW())continue; for(node it:adj[v.getV()]) { if(dist[it.getV()]>it.getW()+dist[v.getV()]) { dist[it.getV()]=(int) (it.getW()+dist[v.getV()]); pq.add(new node(it.getV(),dist[it.getV()])); path[it.getV()]=path[v.getV()]; } else if(dist[it.getV()]==it.getW()+dist[v.getV()]) { path[it.getV()]+=path[v.getV()]; } } } int sum=0; for(int i=1;i<n;i++){ System.out.println(dist[i]); sum+=dist[i]; } return sum; } private static void setGraph(int n,int m){ vis=new boolean[n+1]; indeg=new int[n+1]; // adj=new ArrayList<ArrayList<Integer>>(); // for(int i=0;i<=n;i++)adj.add(new ArrayList<>()); // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // adj.get(u).add(v); // adj.get(v).add(u); // } adj=new ArrayList[n+1]; // backadj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); // backadj[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++){ int u=s.nextInt(),v=s.nextInt(); adj[u].add(v); adj[v].add(u); // backadj[v].add(u); indeg[v]++; indeg[u]++; } // weighted adj // adj=new ArrayList[n+1]; // for(int i=0;i<=n;i++){ // adj[i]=new ArrayList<node>(); // } // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // long w=s.nextInt(); // adj[u].add(new node(v,w)); //// adj[v].add(new node(u,w)); // } } // *********************************GRAPHS-ENDS**************************************************** static int[][] dirs8 = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}; static int[][] dirs4 = {{1,0},{-1,0},{0,1},{0,-1}}; //d-u-r-l static long MOD=(long) (1e9+7); static int prebitsum[][]; static boolean[] vis; static int[]indeg; // static ArrayList<ArrayList<Integer>>adj; static ArrayList<Integer> adj[]; static ArrayList<Integer> backadj[]; static FastReader s = new FastReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException{ // sieve(); // computeFact((int)1e7+1,MOD); // prebitsum=new int[2147483648][31]; // presumbit(prebitsum); // powof2S(); // try { int tt = s.nextInt(); // int tt=1; for(int i=1;i<=tt;i++) { solver(); } out.close(); // catch(Exception e) {return;} } private static void solver() { int n=s.nextInt(); int[]a=s.rdia(n); int[][]ac=new int[n][n]; //a<c int[][]bd=new int[n][n]; //b>d for(int i=n-1;i>=0;i--) { for(int j=i-1;j>=0;j--) { ac[i][j]+=ac[i][j+1]; if(a[i]>a[j])ac[i][j]++; } } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { bd[i][j]+=bd[i][j-1]; if(a[i]>a[j])bd[i][j]++; } } // pi2d(bd); // pi2d(ac); long ans=0l; for(int i=1;i<n;i++){ for(int j=n-2;j>i;j--){ int left = ac[j][0]-ac[j][i]; int right = bd[i][n-1] - bd[i][j]; ans += (left*right); } } out.println(ans); } static int swaps; private static int mergeAndCount(char[] arr, int l,int m, int r){ char[] left = Arrays.copyOfRange(arr, l, m + 1); char[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l; boolean f=false; while (i < left.length && j < right.length) { if (left[i]-'0' <= right[j]-'0')arr[k++] = left[i++]; else { arr[k++] = right[j++]; f=true; } } if(f)swaps++; while (i < left.length)arr[k++] = left[i++]; while (j < right.length)arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(char[] arr, int l, int r) { int count = 0; if (l < r) { int m = (l + r) / 2; count += mergeSortAndCount(arr, l, m); count += mergeSortAndCount(arr, m + 1, r); count += mergeAndCount(arr, l, m, r); } return count; } private static long sqroot(long x) {long left = 0, right = 2000000123;while (right > left) {long mid = (left + right) / 2;if (mid * mid > x) right = mid;else left = mid + 1;}return left - 1;} /* *********************BITS && TOOLS &&DEBUG STARTS***********************************************/ static boolean issafe(int i, int j, int r,int c,boolean[][]vis){ if (i < 0 || j < 0 || i >= r || j >= c||vis[i][j]==true)return false; else return true; } static void presumbit(int[][]prebitsum) { for(int i=1;i<=200000;i++) { int z=i; int j=0; while(z>0) { if((z&1)==1) { prebitsum[i][j]+=(prebitsum[i-1][j]+1); }else { prebitsum[i][j]=prebitsum[i-1][j]; } z=z>>1; j++; } } } static void countOfSetBit(long[]a) { for(int j=30;j>=0;j--) { int cnt=0; for(long i:a) { if((i&1<<j)==1)cnt++; } // printing the current no set bit in all array element System.out.println(cnt); } } public static String revStr(String str){String input = str;StringBuilder input1 = new StringBuilder();input1.append(input);input1.reverse();return input1.toString();} static void pl1d(long[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pb1d(boolean[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pi1d(int[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pc1d(char[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pb2d(boolean[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pc2d(char[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pi2d(int[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pl2d(long[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} // *****************BITS && TOOLS &&DEBUG ENDS*********************************************** } // **************************I/O************************* class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastReader(InputStream stream) {reader = new BufferedReader(new InputStreamReader(stream), 32768);tokenizer = null;} public String next() {while (tokenizer == null || !tokenizer.hasMoreTokens()) {try {tokenizer = new StringTokenizer(reader.readLine());} catch (IOException e) {throw new RuntimeException(e);}}return tokenizer.nextToken();} public int nextInt(){ return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() {String str = "";try {str = reader.readLine();}catch (IOException e) {e.printStackTrace();}return str;} public int[] rdia(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = nextInt();return a;} public long[] rdla(int n) {long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} public Integer[] rdIa(int n) {Integer[] a = new Integer[n];for (int i = 0; i < n; i++) a[i] =nextInt();return a;} public Long[] rdLa(int n) {Long[] a = new Long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} } class dsu{ int n; static int parent[]; static int rank[]; static int[]Size; public dsu(int n) {this.n=n;this.parent=new int[n];this.rank=new int[n];this.Size=new int[n]; for(int i=0;i<n;i++){parent[i]=i;rank[i]=0;Size[i]=1;} } static int findpar(int node) {if(node==parent[node])return node;return parent[node]=findpar(parent[node]);} static void union(int u,int v){ u=findpar(u);v=findpar(v); if(u!=v) { if(rank[u]<rank[v]) {parent[u]=v;Size[v]+=Size[u];} else if(rank[v]<rank[u]) {parent[v]=u;Size[u]+=Size[v];} else{parent[v]=u;rank[u]++;Size[u]+=Size[v];} } } } class pair{ int x;int y; long u,v; public pair(int x,int y){this.x=x;this.y=y;} public pair(long u,long v) {this.u=u;this.v=v;} } class Tuple{ String str;int x;int y; public Tuple(String str,int x,int y) { this.str=str; this.x=x; this.y=y; } } class node implements Comparator<node>{ private int v; private long w; node(int _v, long _w) { v = _v; w = _w; } node() {} int getV() { return v; } long getW() { return w; } @Override public int compare(node node1, node node2) { if (node1.w < node2.w) return -1; if (node1.w > node2.w) return 1; return 0; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
f9acb1cc51ca49f87ec6c54704064cdc
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// OM NAMAH SHIVAY import java.math.BigInteger; import java.util.*; import java.io.*; public class Vaibhav { static long bit[]; static boolean prime[]; static class Pair implements Comparable<Pair> { long x; int y; Pair(long x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o){ return (int)(this.x-o.x); } } static long power(long x, long y, long p) { if (y == 0) return 1; if (x == 0) return 0; long res = 1l; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if (y == 0) return 1; if (x == 0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readlongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static int binomialCoeff(int n, int r) { if (r > n) return 0; long m = 1000000007; long inv[] = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans; } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static BigInteger bi(String str) { return new BigInteger(str); } // Author - vaibhav_1710 static FastScanner fs = null; static long mod=998244353; static ArrayList<Integer> al[]; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t =fs.nextInt(); outer: while (t-- > 0 ){ int n = fs.nextInt(); int a[] = fs.readArray(n); int fr[][] = new int[n][n]; int br[][] = new int[n][n]; for(int i=0;i<n;i++){ for(int j=i-1;j>=0;j--){ fr[i][j] += fr[i][j+1]; if(a[i]>a[j])fr[i][j]++; } } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ br[i][j] += br[i][j-1]; if(a[i]>a[j]) br[i][j]++; } } long ans=0l; for(int i=1;i<n;i++){ for(int j=n-2;j>i;j--){ int left = fr[j][0] - fr[j][i]; int right = br[i][n-1] - br[i][j]; ans += (left*right); } } out.println(ans); } out.close(); } public static long query(int a,int b){ System.out.println("? "+a+" "+b); System.out.flush(); long v = fs.nextLong(); return v; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
180a91e2e893c055c4020e9d33fbd455
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.function.IntToLongFunction; // C -> CodeForcesProblemSet public final class C { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static int t = 1; static double epsilon = 0.00000001; static boolean[] isPrime; static int[] smallestFactorOf; @SuppressWarnings("unused") public static void main(String[] args) throws Exception { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); int[] perm = fr.nextIntArray(n); // (a, b, c, d) such that // pa < pc and pb > pd // amongst elements after pb, we want to // know the following: // // a. Number of elements greater than pa // b. Number of elements less than pb int[][] cntFromUpto = new int[n][n + 1]; cntFromUpto[n - 1] = new int[n + 1]; cntFromUpto[n - 1][perm[n - 1]]++; for (int i = 1; i < n + 1; i++) cntFromUpto[n - 1][i] += cntFromUpto[n - 1][i - 1]; for (int i = n - 2; i > -1; i--) { cntFromUpto[i] = cntFromUpto[i + 1].clone(); cntFromUpto[i][perm[i]]++; for (int j = perm[i] + 1; j < n + 1; j++) cntFromUpto[i][j]++; } int[][] cntUptoUpto = new int[n][n + 1]; cntUptoUpto[0] = new int[n + 1]; cntUptoUpto[0][perm[0]]++; for (int i = 1; i < n + 1; i++) cntUptoUpto[0][i] += cntUptoUpto[0][i - 1]; for (int i = 1; i < n; i++) { cntUptoUpto[i] = cntUptoUpto[i - 1].clone(); cntUptoUpto[i][perm[i]]++; for (int j = perm[i] + 1; j < n + 1; j++) cntUptoUpto[i][j]++; } long ans = 0; for (int b = 1; b < n - 2; b++) for (int c = b + 1; c < n - 1; c++) { // to the left of 'b', smaller than pc // to the right of 'c', smaller than pb int pc = perm[c], pb = perm[b]; int[] befCnt = cntUptoUpto[b - 1]; int numSmallerPc = befCnt[pc - 1]; int[] aftCnt = cntFromUpto[c + 1]; int numSmallerPb = aftCnt[pb - 1]; ans += (long) numSmallerPb * numSmallerPc; } out.println(ans); } out.close(); } static class Pair { long a, b; Pair(long aa, long bb) { a = aa; b = bb; } } static class SegmentBeatExt implements Cloneable { private static long inf = (long) 2e18; private SegmentBeatExt left; private SegmentBeatExt right; private long firstLargest; private long secondLargest; private int firstLargestCnt; private long firstSmallest; private long secondSmallest; private int firstSmallestCnt; private long dirty; private int size; private long sum; private void setMin(long x) { if (firstLargest <= x) { return; } sum -= (firstLargest - x) * firstLargestCnt; firstLargest = x; if (firstSmallest >= x) { firstSmallest = x; firstSmallestCnt = size; } secondSmallest = Math.min(secondSmallest, x); if (secondSmallest == firstSmallest) { secondSmallest = inf; } } private void setMax(long x) { if (firstSmallest >= x) { return; } sum += (x - firstSmallest) * firstSmallestCnt; firstSmallest = x; if (firstLargest <= x) { firstLargest = x; firstLargestCnt = size; } secondLargest = Math.max(secondLargest, x); if (secondLargest == firstLargest) { secondLargest = -inf; } } private void modify(long x) { dirty += x; sum += x * size; firstSmallest += x; firstLargest += x; secondSmallest += x; secondLargest += x; } public void pushUp() { firstLargest = Math.max(left.firstLargest, right.firstLargest); secondLargest = Math.max(left.firstLargest == firstLargest ? left.secondLargest : left.firstLargest, right.firstLargest == firstLargest ? right.secondLargest : right.firstLargest); firstLargestCnt = (left.firstLargest == firstLargest ? left.firstLargestCnt : 0) + (right.firstLargest == firstLargest ? right.firstLargestCnt : 0); firstSmallest = Math.min(left.firstSmallest, right.firstSmallest); secondSmallest = Math.min(left.firstSmallest == firstSmallest ? left.secondSmallest : left.firstSmallest, right.firstSmallest == firstSmallest ? right.secondSmallest : right.firstSmallest); firstSmallestCnt = (left.firstSmallest == firstSmallest ? left.firstSmallestCnt : 0) + (right.firstSmallest == firstSmallest ? right.firstSmallestCnt : 0); sum = left.sum + right.sum; size = left.size + right.size; } public void pushDown() { if (dirty != 0) { left.modify(dirty); right.modify(dirty); dirty = 0; } left.setMin(firstLargest); right.setMin(firstLargest); left.setMax(firstSmallest); right.setMax(firstSmallest); } public SegmentBeatExt(int l, int r, IntToLongFunction func) { if (l < r) { int m = DigitUtils.floorAverage(l, r); left = new SegmentBeatExt(l, m, func); right = new SegmentBeatExt(m + 1, r, func); pushUp(); } else { sum = firstSmallest = firstLargest = func.applyAsLong(l); firstSmallestCnt = firstLargestCnt = 1; secondSmallest = inf; secondLargest = -inf; size = 1; } } private boolean covered(int ll, int rr, int l, int r) { return ll <= l && rr >= r; } private boolean noIntersection(int ll, int rr, int l, int r) { return ll > r || rr < l; } public void updateMin(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { if (firstLargest <= x) { return; } if (secondLargest < x) { setMin(x); return; } } pushDown(); int m = DigitUtils.floorAverage(l, r); left.updateMin(ll, rr, l, m, x); right.updateMin(ll, rr, m + 1, r, x); pushUp(); } public void updateMax(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { if (firstSmallest >= x) { return; } if (secondSmallest > x) { setMax(x); return; } } pushDown(); int m = DigitUtils.floorAverage(l, r); left.updateMax(ll, rr, l, m, x); right.updateMax(ll, rr, m + 1, r, x); pushUp(); } public void update(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { modify(x); return; } pushDown(); int m = DigitUtils.floorAverage(l, r); left.update(ll, rr, l, m, x); right.update(ll, rr, m + 1, r, x); pushUp(); } public long querySum(int ll, int rr, int l, int r) { if (noIntersection(ll, rr, l, r)) { return 0; } if (covered(ll, rr, l, r)) { return sum; } pushDown(); int m = DigitUtils.floorAverage(l, r); return left.querySum(ll, rr, l, m) + right.querySum(ll, rr, m + 1, r); } private SegmentBeatExt deepClone() { SegmentBeatExt seg = clone(); if (seg.left != null) { seg.left = seg.left.deepClone(); } if (seg.right != null) { seg.right = seg.right.deepClone(); } return seg; } protected SegmentBeatExt clone() { try { return (SegmentBeatExt) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private void toString(StringBuilder builder) { if (left == null && right == null) { builder.append(sum).append(","); return; } pushDown(); left.toString(builder); right.toString(builder); } public String toString() { StringBuilder builder = new StringBuilder(); deepClone().toString(builder); if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } static class DigitUtils { private DigitUtils() { } public static int floorAverage(int x, int y) { return (x & y) + ((x ^ y) >> 1); } } } static class Tuple { char c; int idx; Tuple(char cc, int ii) { c = cc; idx = ii; } } static class Segment { long li, ri; Segment (long ll, long rr) { li = ll; ri = rr; } } static int diff(char[] s1, char[] s2) { int diff = 0; for (int i = 0; i < s1.length; i++) diff += Math.abs(s1[i] - s2[i]); return diff; } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { char[] line = fr.next().toCharArray(); for (int j = 0; j < m; j++) grid[i][j] = line[j] - 48; } return grid; } } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(ArrayList<Point>[] outFrom, int root) { n = outFrom.length; height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(outFrom, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(ArrayList<Point>[] outFrom, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (Point to : outFrom[node]) { if (!visited[(int) to.x]) { dfs(outFrom, (int) to.x, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static final class RedBlackCountSet { // Manual implementation of RB-BST for C++ PBDS functionality. // Modification required according to requirements. // Colors for Nodes: private static final boolean RED = true; private static final boolean BLACK = false; // Pointer to the root: private Node root; // Public constructor: public RedBlackCountSet() { root = null; } // Node class for storing key value pairs: private class Node { long key; long value; Node left, right; boolean color; long size; // Size of the subtree rooted at that node. public Node(long key, long value, boolean color) { this.key = key; this.value = value; this.left = this.right = null; this.color = color; this.size = value; } } /***** Invariant Maintenance functions: *****/ // When a temporary 4 node is formed: private Node flipColors(Node node) { node.left.color = node.right.color = BLACK; node.color = RED; return node; } // When there's a right leaning red link and it is not a 3 node: private Node rotateLeft(Node node) { Node rn = node.right; node.right = rn.left; rn.left = node; rn.color = node.color; node.color = RED; return rn; } // When there are 2 red links in a row: private Node rotateRight(Node node) { Node ln = node.left; node.left = ln.right; ln.right = node; ln.color = node.color; node.color = RED; return ln; } /***** Invariant Maintenance functions end *****/ // Public functions: public void put(long key) { root = put(root, key); root.color = BLACK; // One of the invariants. } private Node put(Node node, long key) { // Standard insertion procedure: if (node == null) return new Node(key, 1, RED); // Recursing: int cmp = Long.compare(key, node.key); if (cmp < 0) node.left = put(node.left, key); else if (cmp > 0) node.right = put(node.right, key); else node.value++; // Invariant maintenance: if (node.left != null && node.right != null) { if (node.right.color = RED && node.left.color == BLACK) node = rotateLeft(node); if (node.left.color == RED && node.left.left.color == RED) node = rotateRight(node); if (node.left.color == RED && node.right.color == RED) node = flipColors(node); } // Property maintenance: node.size = node.value + size(node.left) + size(node.right); return node; } private long size(Node node) { if (node == null) return 0; else return node.size; } public long rank(long key) { return rank(root, key); } // Modify according to requirements. private long rank(Node node, long key) { if (node == null) return 0; int cmp = Long.compare(key, node.key); if (cmp < 0) return rank(node.left, key); else if (cmp > 0) return node.value + size(node.left) + rank(node.right, key); else return node.value + size(node.left); } } static class SegmentTree { private Node[] heap; private int[] array; private int size; public SegmentTree(int[] array) { this.array = Arrays.copyOf(array, array.length); //The max size of this array is about 2 * 2 ^ log2(n) + 1 size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1))); heap = new Node[size]; build(1, 0, array.length); } public int size() { return array.length; } //Initialize the Nodes of the Segment tree private void build(int v, int from, int size) { heap[v] = new Node(); heap[v].from = from; heap[v].to = from + size - 1; if (size == 1) { heap[v].sum = array[from]; heap[v].min = array[from]; heap[v].minCnt = 1; } else { //Build childs build(2 * v, from, size / 2); build(2 * v + 1, from + size / 2, size - size / 2); heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum; //min = min of the children heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); if (heap[2 * v].min == heap[2 * v + 1].min) heap[v].minCnt = heap[2 * v].minCnt + heap[2 * v + 1].minCnt; else if (heap[2 * v].min < heap[2 * v + 1].min) heap[v].minCnt = heap[2 * v].minCnt; else heap[v].minCnt = heap[2 * v + 1].minCnt; } } public int rsq(int from, int to) { return rsq(1, from, to); } private int rsq(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Sum without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return (to - from + 1) * n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].sum; } if (intersects(from, to, n.from, n.to)) { propagate(v); int leftSum = rsq(2 * v, from, to); int rightSum = rsq(2 * v + 1, from, to); return leftSum + rightSum; } return 0; } public int rMinQ(int from, int to) { return rMinQ(1, from, to); } private int rMinQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].min; } if (intersects(from, to, n.from, n.to)) { propagate(v); int leftMin = rMinQ(2 * v, from, to); int rightMin = rMinQ(2 * v + 1, from, to); return Math.min(leftMin, rightMin); } return Integer.MAX_VALUE; } public int rMinCntQ(int from, int to) { return rMinCntQ(1, from, to); } private int rMinCntQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].min; } if (intersects(from, to, n.from, n.to)) { propagate(v); int leftMin = rMinQ(2 * v, from, to); int rightMin = rMinQ(2 * v + 1, from, to); int leftMinCnt = rMinCntQ(2 * v, from, to); int rightMinCnt = rMinCntQ(2 * v + 1, from, to); if (leftMin == rightMin && leftMin != Integer.MAX_VALUE) return leftMinCnt + rightMinCnt; else if (leftMin < rightMin) return leftMinCnt; else if (rightMin < leftMin) return rightMinCnt; } return Integer.MAX_VALUE; } public void update(int from, int to, int value) { update(1, from, to, value); } private void update(int v, int from, int to, int value) { //The Node of the heap tree represents a range of the array with bounds: [n.from, n.to] Node n = heap[v]; if (contains(from, to, n.from, n.to)) { change(n, value); } if (n.size() == 1) return; if (intersects(from, to, n.from, n.to)) { propagate(v); update(2 * v, from, to, value); update(2 * v + 1, from, to, value); n.sum = heap[2 * v].sum + heap[2 * v + 1].sum; n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); if (heap[2 * v].min == heap[2 * v + 1].min && heap[2 * v].min != Integer.MAX_VALUE) n.minCnt = heap[2 * v].minCnt + heap[2 * v + 1].minCnt; else if (heap[2 * v].min == heap[2 * v + 1].min) n.minCnt = heap[2 * v + 1].minCnt; else if (heap[2 * v].min < heap[2 * v + 1].min) n.minCnt = heap[2 * v].minCnt; else n.minCnt = heap[2 * v + 1].minCnt; } } //Propagate temporal values to children private void propagate(int v) { Node n = heap[v]; if (n.pendingVal != null) { change(heap[2 * v], n.pendingVal); change(heap[2 * v + 1], n.pendingVal); n.pendingVal = null; //unset the pending propagation value } } //Save the temporal values that will be propagated lazily private void change(Node n, int value) { n.pendingVal = value; n.sum = n.size() * value; n.min = value; n.minCnt = n.size(); array[n.from] = value; } //Test if the range1 contains range2 private boolean contains(int from1, int to1, int from2, int to2) { return from2 >= from1 && to2 <= to1; } //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2] private boolean intersects(int from1, int to1, int from2, int to2) { return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..) || from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..).. } //The Node class represents a partition range of the array. static class Node { int sum; int min; //Here We store the value that will be propagated lazily Integer pendingVal = null; int from; int to; int minCnt; int size() { return to - from + 1; } } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { if (super.containsKey(key)) { return super.put(key, super.get(key) + 1); } else { return super.put(key, 1); } } public Integer removeCM(T key) { Integer count = super.get(key); if (count == null) return -1; if (count == 1) return super.remove(key); else return super.put(key, super.get(key) - 1); } public Integer getCM(T key) { Integer count = super.get(key); if (count == null) return 0; return count; } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static class Point implements Comparable<Point> { long x; long y; long id; Point() { x = y = id = 0; } Point(Point p) { this.x = p.x; this.y = p.y; this.id = p.id; } Point(long a, long b, long id) { this.x = a; this.y = b; this.id = id; } Point(long a, long b) { this.x = a; this.y = b; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; return 0; } public boolean equals(Point that) { return this.compareTo(that) == 0; } } static int longestPrefixPalindromeLen(char[] s) { int n = s.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(s[i]); StringBuilder sb2 = new StringBuilder(sb); sb.append('^'); sb.append(sb2.reverse()); // out.println(sb.toString()); char[] newS = sb.toString().toCharArray(); int m = newS.length; int[] pi = piCalcKMP(newS); return pi[m - 1]; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static String toBinaryString(long num, int bits) { StringBuilder sb = new StringBuilder(Long.toBinaryString(num)); sb.reverse(); for (int i = sb.length(); i < bits; i++) sb.append('0'); return sb.reverse().toString(); } static long modDiv(long a, long b) { return mod(a * power(b, gigamod - 2, gigamod)); } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static long hash(long i) { return (i * 2654435761L % gigamod); } static long hash2(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static double distance(Point p1, Point p2) { return Math.sqrt(Math.pow(p2.y-p1.y, 2) + Math.pow(p2.x-p1.x, 2)); } /*static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(200001); CountMap<Integer> fnps = new CountMap<>(); while (num != 1) { fnps.putCM(smallestFactorOf[num]); num /= smallestFactorOf[num]; } return fnps; }*/ static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static int bsearch(int[] arr, int val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { // Returns the index of the last element // smaller than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long factorial(long n) { if (n <= 1) return 1; long factorial = 1; for (int i = 1; i <= n; i++) factorial = mod(factorial * i); return factorial; } static long factorialInDivision(long a, long b) { if (a == b) return 1; if (b < a) { long temp = a; a = b; b = temp; } long factorial = 1; for (long i = a + 1; i <= b; i++) factorial = mod(factorial * i); return factorial; } static long nCr(long n, long r, long[] fac) { long p = 998244353; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r /*long fac[] = new long[(int)n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p;*/ return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nPr(long n, long r) { return factorialInDivision(n, n - r); } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static String toString(int[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(boolean[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(long[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(char[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + ""); return sb.toString(); } static String toString(int[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(long[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(double[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(char[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static long mod(long a, long m) { return (a%m + m) % m; } static long mod(long num) { return (num % gigamod + gigamod) % gigamod; } } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5249b5438dae6861cd0ed5cd5d59ff7a
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// Problem: C. Tokitsukaze and Strange Inequality // Contest: Codeforces - Codeforces Round #789 (Div. 2) // URL: https://codeforces.com/contest/1678/problem/C // Memory Limit: 256 MB // Time Limit: 1500 ms // // Powered by CP Editor (https://cpeditor.org) import java.util.*; public class Mytemplate { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0){ t--; int n=sc.nextInt(); int[] pre= new int[n]; for(int i=0;i<n;i++){ pre[i]=sc.nextInt(); } // .......b.....c......... // x y // ans+=(x*y); int[][] br= new int[n][n]; for(int i=n-1;i>1;i--){ int temp=0; for(int j=i-1;j>=0;j--){ if(pre[j]<pre[i]){ temp++; } br[i][j]=temp; } } int[][] cr= new int[n][n]; for(int i=0;i<n;i++){ int temp=0; for(int j=i+1;j<n;j++){ if(pre[i]>pre[j]){ temp++; } cr[i][j]=temp; } } long ans=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ // i b he or j c int temp1=br[j][0]-br[j][i]; int temp2=cr[i][n-1]-cr[i][j]; ans=ans+temp1*temp2; } } System.out.println(ans); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
4be1e848e710b06d140732c9fcfdb0c4
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } long ans=0; for(int i=0;i<n;i++) { int arr[]=new int[n+1]; int brr[]=new int[n+1]; for(int j=i+2;j<n;j++) { int v=a[j]; update(arr,1,v,n); } long val=0; for(int j=i+2;j<n;j++) { update(arr,-1,a[j],n); int s=sum(brr,n)-sum(brr,a[j]); val-=s; update(brr,1,a[j-1],n); s=sum(arr,a[j-1]-1); val+=s; if(a[j]>a[i]) { ans+=val; } } } out.println(ans); } out.close(); } public static int sum(int a[],int k) { int sum=0; while(k>=1) { sum+=a[k]; k-=k&-k; } return sum; } public static void update(int a[],int d,int k,int n) { while(k<=n) { a[k]+=d; k+=k&-k; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
0297fef2d49e1405fadbc78ac3c71f83
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { static int t,n,arr[],pre[][]; static Scanner sc=new Scanner(System.in); static BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer in=new StreamTokenizer(bf); static PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException{ in.nextToken();t=(int)in.nval; while(t-->0) solve(); out.flush(); } static void solve() throws IOException { in.nextToken();n=(int)in.nval; arr=new int[n]; for(int i=0;i<n;++i){ in.nextToken();arr[i]=(int)in.nval; } pre=new int[n][n+1]; for(int i=0;i<n;++i){ for(int j=1;j<=n;++j){ if(arr[i]>arr[j-1]) pre[i][j]++; pre[i][j]+=pre[i][j-1]; } } long ans=0; for(int i=1;i<n;++i) for(int j=i+1;j<n;++j) ans+=(pre[i][n]-pre[i][j+1])*(pre[j][i]-pre[j][0]); out.println(ans); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
a4b926eb6402fcbf436ccc560507eee1
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; /** * # * * @author pttrung */ public class C_Round_789_Div2 { public static int MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int z = 0; z < T; z++) { int n = in.nextInt(); int[] data = new int[n]; for (int i = 0; i < data.length; i++) { data[i] = in.nextInt(); } int[][] less = new int[n][n]; int[][] more = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (j > 0) { less[i][j] += less[i][j - 1]; } if (data[j] < data[i]) { less[i][j]++; } } for (int j = n - 1; j > i; j--) { if (j + 1 < n) { more[i][j] += more[i][j + 1]; } if (data[i] > data[j]) { more[i][j]++; } } } long re = 0; for (int i = 1; i < n; i++) { for (int j = i + 1; j + 1 < n; j++) { long a = less[j][i - 1]; long b = more[i][j + 1]; re += a * b; } } out.println(re); } out.close(); } static long abs(long a) { return a < 0 ? -a : a; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point { int x; int y; public Point(int start, int end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return (val * val); } else { return (val * ((val * a))); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
19566e4ae413051a7b208408dfbf1e75
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static long cr[][]=new long[1001][1001]; //static double EPS = 1e-7; static long mod=998244353; static long val=0; static boolean flag=true; public static void main(String[] args) { FScanner sc = new FScanner(); //Arrays.fill(prime, true); //sieve(); //ncr(); int t=sc.nextInt(); StringBuilder sb = new StringBuilder(); while(t-->0) { int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int dp[][]=new int[n+1][n+1]; for(int i=n-1;i>=0;i--) { for(int j=0;j<=n;j++) dp[i][j]=dp[i+1][j]; for(int j=arr[i]+1;j<=n;j++ ) { dp[i][j]++; } } long ans=0; for(int i=1;i<n-2;i++) { for(int j=i+1;j<n-1;j++) { ans+=dp[j+1][arr[i]]*(dp[0][arr[j]]-dp[i][arr[j]]); } } sb.append(ans); sb.append("\n"); } System.out.println(sb.toString()); } public static int solve(char c[],int prev,int i,int dp[][]) { if(i+1>=c.length) return 0; if(dp[prev][i]!=-1) return dp[prev][i]; int res=0; if(c[i]!=c[i+1]) res=Math.min( solve(c,prev,i+2,dp),1+solve(c,1-prev,i+2,dp)); else if(prev!=c[i]-'0') res= 1+solve(c,c[i]-'0',i+2,dp); else res=solve(c,c[i]-'0',i+2,dp); dp[prev][i]=res; return res; } public static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % mod; } n = n / 2; x = x * x % mod; } return result; } public static long gcd(long a,long b) { return b==0 ? a:gcd(b,a%b); } /* public static void sieve() { prime[0]=prime[1]=false; int n=1000000; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } */ public static void ncr() { cr[0][0]=1; for(int i=1;i<=1000;i++) { cr[i][0]=1; for(int j=1;j<i;j++) { cr[i][j]=(cr[i-1][j-1]+cr[i-1][j])%mod; } cr[i][i]=1; } } } class pair //implements Comparable<pair> { long a;long b; pair(long a,long b) { this.b=b; this.a=a; } } class FScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer sb = new StringTokenizer(""); String next(){ while(!sb.hasMoreTokens()){ try{ sb = new StringTokenizer(br.readLine()); } catch(IOException e){ } } return sb.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt(){ return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } float nextFloat(){ return Float.parseFloat(next()); } double nextDouble(){ return Double.parseDouble(next()); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
84ac739d946db49f38561a88d672cb02
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /* * Author: Atuer */ public class C_WA { // ==== Solve Code ====// static int INF = 2000000010; public static void csh() { } public static void main(String[] args) throws IOException { // csh(); int t = in.nextInt(); while (t-- > 0) { solve(); out.flush(); } out.close(); } public static void solve() { int n = in.nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = in.nextInt(); // 从1~i中小于j的数量 int[][] pre = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) pre[i][j] = pre[i - 1][j]; for (int j = a[i] + 1; j <= n; j++) pre[i][j]++; } // for (int i = 1; i <= n; i++) // out.println(Arrays.toString(pre[i])); long ans = 0; for (int b = 1; b <= n; b++) for (int c = b + 1; c <= n; c++) ans += 1l * pre[b - 1][a[c]] * (pre[n][a[b]] - pre[c][a[b]]); out.println(ans); } public static class Node { int x, y, k; public Node(int x, int y, int k) { this.x = x; this.y = y; this.k = k; } } // ==== Solve Code ====// // ==== Template ==== // public static long cnm(int a, int b) { long sum = 1; int i = a, j = 1; while (j <= b) { sum = sum * i / j; i--; j++; } return sum; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static void gbSort(int[] a, int l, int r) { if (l < r) { int m = (l + r) >> 1; gbSort(a, l, m); gbSort(a, m + 1, r); int[] t = new int[r - l + 1]; int idx = 0, i = l, j = m + 1; while (i <= m && j <= r) if (a[i] <= a[j]) t[idx++] = a[i++]; else t[idx++] = a[j++]; while (i <= m) t[idx++] = a[i++]; while (j <= r) t[idx++] = a[j++]; for (int z = 0; z < t.length; z++) a[l + z] = t[z]; } } // ==== Template ==== // // ==== IO ==== // static InputStream inputStream = System.in; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(System.out); static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { return false; // TODO: handle exception } } return true; } public String nextLine() { String str = null; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } // ==== IO ==== // }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
8fd0dd19500af98a43259e89e8e3cfa1
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static BufferedReader bf; static PrintWriter out; public static void main (String[] args)throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int t = Integer.parseInt(bf.readLine()); while(t-->0){ solve(); } } public static void solve()throws IOException{ int n = nextInt(); int []arr = nextIntArray(n); long[][]mat = new long[n][n]; for(int i =2;i<n-1;i++){ int count = 0; for(int j = 0;j<i;j++){ mat[j][i] += mat[j][i-1]+count; if(arr[i] > arr[j]){ count++; } } } long count = 0; for(int i = n-3;i>=1;i--){ for(int j = n-1;j>i+1;j--){ if(arr[i] > arr[j]){ count += (mat[i][j-1]); // println(i+" "+(j)+" "+(mat[i][j-1])); } } } // for(int i =0;i<n;i++){ // println(Arrays.toString(mat[i])); // } println(count); } public static int check(long mid,int []arr,long count){ for(int i = 0;i<arr.length;i++){ if(arr[i] != 0){ count = count - (mid - arr[i]); } } if(count == 0)return 0; if(count < 0)return -1; return 1; } // code for input public static void print(String s ){ System.out.print(s); } public static void print(int num ){ System.out.print(num); } public static void print(long num ){ System.out.print(num); } public static void println(String s){ System.out.println(s); } public static void println(int num){ System.out.println(num); } public static void println(long num){ System.out.println(num); } public static void println(){ System.out.println(); } public static int toInt(String s){ return Integer.parseInt(s); } public static long toLong(String s){ return Long.parseLong(s); } public static String[] nextStringArray()throws IOException{ return bf.readLine().split(" "); } public static int nextInt()throws IOException{ return Integer.parseInt(bf.readLine()); } public static long nextLong()throws IOException{ return Long.parseLong(bf.readLine()); } public static String nextString()throws IOException{ return bf.readLine(); } public static int[] nextIntArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); int[]arr = new int[n]; for(int i =0;i<n;i++){ arr[i] = Integer.parseInt(str[i]); } return arr; } public static long[] nextLongArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); long[]arr = new long[n]; for(int i =0;i<n;i++){ arr[i] = Long.parseLong(str[i]); } return arr; } public static int[][] newIntMatrix(int r,int c)throws IOException{ int[][]arr = new int[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Integer.parseInt(str[j]); } } return arr; } public static long[][] newLongMatrix(int r,int c)throws IOException{ long[][]arr = new long[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Long.parseLong(str[j]); } } return arr; } static class pair{ int one; int two; pair(int one,int two){ this.one = one ; this.two =two; } } public static long gcd(long a,long b){ if(b == 0)return a; return gcd(b,a%b); } public static long lcm(long a,long b){ return (a*b)/(gcd(a,b)); } public static boolean isPalindrome(String s){ int i = 0; int j = s.length()-1; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } } // use some math tricks it might help // sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently // always use long number to do 10^9+7 modulo // if a problem is related to binary string it could also be related to parenthesis // *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work****** // try sorting // try to think in opposite direction of question it might work in your way // if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general // if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work. // in range query sums try to do binary search it could work // analyse the time complexity of program thoroughly // anylyse the test cases properly // if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required // try to do the opposite operation of what is given in the problem //think about the base cases properly //If a question is related to numbers try prime factorisation or something related to number theory // keep in mind unique strings
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
3f028f4cd43f973484b728537a78c3b5
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/** * @author vivek * programming is thinking, not typing */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { private static void solveTC(int __) { /* For Google */ // ans.append("Case #").append(__).append(": "); //code start int n= scn.nextInt(); int[] arr= scn.nextIntArray(n); int[][] leftFreq = new int[n][n+1]; int[][] rightFreq = new int[n][n+1]; int[] freq = new int[n+1]; for (int i = 0; i < n-1; i++) { freq[arr[i]]++; leftFreq[i+1] = Arrays.copyOf(freq, freq.length); } for (int i = 1; i <= n; i++) { for (int j = 0; j < n ; j++) { leftFreq[j][i]+=leftFreq[j][i-1]; // System.out.print(leftFreq[j][i]+" "); } // System.out.println(); } freq = new int[n+1]; for (int i = n-1; i > 0; i--) { freq[arr[i]]++; rightFreq[i-1] = Arrays.copyOf(freq, freq.length); } for (int i = 1; i <= n; i++) { for (int j = 0; j < n ; j++) { rightFreq[j][i]+=rightFreq[j][i-1]; // System.out.print(rightFreq[j][i]+" "); } // System.out.println(); } long ans = 0; for (int b = 0; b < n; b++) { for (int c = b+1; c < n; c++) { long achoices = leftFreq[b][arr[c]]; long dchoices = rightFreq[c][arr[b]]; ans += achoices * dchoices; } } print(ans); //code end print("\n"); } public static void main(String[] args) { scn = new Scanner(); ans = new StringBuilder(); int t = scn.nextInt(); // int t = 1; // int limit= ; // sieve(limit); /* try { System.setOut(new PrintStream(new File("file_i_o\\output.txt"))); } catch (FileNotFoundException e) { e.printStackTrace(); } */ for (int i = 1; i <= t; i++) { solveTC(i); } System.out.print(ans); } //Stuff for prime start /** * sorting algos */ private static void sort(int[] arr) { ArrayList<Integer> li = new ArrayList<>(arr.length); for (int ele : arr) li.add(ele); Collections.sort(li); for (int i = 0; i < li.size(); i++) { arr[i] = li.get(i); } } private static void sort(long[] arr) { ArrayList<Long> li = new ArrayList<>(arr.length); for (long ele : arr) li.add(ele); Collections.sort(li); for (int i = 0; i < li.size(); i++) { arr[i] = li.get(i); } } private static void sort(float[] arr) { ArrayList<Float> li = new ArrayList<>(arr.length); for (float ele : arr) li.add(ele); Collections.sort(li); for (int i = 0; i < li.size(); i++) { arr[i] = li.get(i); } } private static void sort(double[] arr) { ArrayList<Double> li = new ArrayList<>(arr.length); for (double ele : arr) li.add(ele); Collections.sort(li); for (int i = 0; i < li.size(); i++) { arr[i] = li.get(i); } } /** * List containing prime numbers <br> * <b>i<sup>th</sup></b> position contains <b>i<sup>th</sup></b> prime number <br> * 0th index is <b>null</b> */ private static ArrayList<Integer> listOfPrimes; /** * query <b>i<sup>th</sup></b> element to get if its prime of not */ private static boolean[] isPrime; /** * Performs Sieve of Erathosnesis and initialise isPrime array and listOfPrimes list * * @param limit the number till which sieve is to be performed */ private static void sieve(int limit) { listOfPrimes = new ArrayList<>(); listOfPrimes.add(null); boolean[] array = new boolean[limit + 1]; Arrays.fill(array, true); array[0] = false; array[1] = false; for (int i = 2; i <= limit; i++) { if (array[i]) { for (long j = (long) i * i; j <= limit; j += i) { array[(int) j] = false; } } } isPrime = array; for (int i = 0; i <= limit; i++) { if (array[i]) { listOfPrimes.add(i); } } } //stuff for prime end /** * Calculates the Least Common Multiple of two numbers * * @param a First number * @param b Second Number * @return Least Common Multiple of <b>a</b> and <b>b</b> */ private static long lcm(long a, long b) { return a * b / gcd(a, b); } /** * Calculates the Greatest Common Divisor of two numbers * * @param a First number * @param b Second Number * @return Greatest Common Divisor of <b>a</b> and <b>b</b> */ private static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static void print(Object obj) { ans.append(obj.toString()); } static Scanner scn; static StringBuilder ans; //Fast Scanner static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); /* try { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt")))); } catch (FileNotFoundException e) { e.printStackTrace(); } */ } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } Integer[] nextIntegerArray(int n) { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } String[] nextStringArray() { return nextLine().split(" "); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
cd4c1b2db5fb59d133dea98d2a5f0d89
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class CF1{ public static void main(String[] args) { FastScanner sc=new FastScanner(); int T=sc.nextInt(); // int T=1; for (int tt=1; tt<=T; tt++){ int n = sc.nextInt(); long ans=0; int arr []= sc.readArray(n); int pre[][]= new int [n][n]; for (int i=0; i<n; i++){ int x =0; for (int j=0; j<i; j++){ if (arr[j]<arr[i]) x++; pre[i][j]=x; } x=0; for (int j=n-1; j>i; j--){ if (arr[j]<arr[i]) x++; pre[i][j]=x; } } for (int i=1; i<n-1; i++){ for (int j=i+1; j<n-1; j++){ long yy= pre[i][j+1]; yy*= pre[j][i-1]; ans+=yy; } } System.out.println(ans); } } static int createPalindrome(int input, int b, int isOdd) { int n = input; int palin = input; if (isOdd == 1) n /= b; while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin; } static ArrayList<Integer> arr; static void generatePalindromes(int n) { int number; for (int j = 0; j < 2; j++) { int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { arr.add(number); i++; } } } static class SegmentTree{ int nodes[]; int arr[]; int lazy[]; public SegmentTree(int n, int arr[]){ nodes = new int [4*n+1]; lazy= new int [4*n+1]; this.arr=arr; build(1,1,n); } private void build (int v, int l , int r){ if (l==r) { nodes[v]=arr[l-1];} else { int m=(l+r)/2; build(2*v,l,m); build(2*v+1,m+1,r); nodes[v]=Math.min(nodes[2*v], nodes[2*v+1]); } } private void push(int v) { nodes[v*2] += lazy[v]; lazy[v*2] += lazy[v]; nodes[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private void update(int v, int l, int r, int x, int y, int add) { if (l>y || r<x) return; if (l>=x && y>=r) { nodes[v]+=add; lazy[v]+=add; } else { push(v); int mid =(l+r)/2; update(2*v,l,mid,x,y,add); update(2*v+1,mid+1,r,x,y,add); nodes[v]=Math.min(nodes[v*2], nodes[v*2+1]); } } private int query(int v, int l, int r, int x, int y){ if (l>y || r<x) return Integer.MAX_VALUE; if (l>=x && r<=y) return nodes[v]; else { int m = (l+r)/2; push(v); return Math.min(query(2*v+1,m+1,r,x,y),query(2*v,l,m,x,y)); } } } static class LPair{ long x,y; LPair(long x , long y){ this.x=x; this.y=y; } } static long prime(long n){ for (long i=3; i*i<=n; i+=2){ if (n%i==0) return i; } return -1; } static long factorial (int x){ if (x==0) return 1; long ans =x; for (int i=x-1; i>=1; i--){ ans*=i; ans%=mod; } return ans; } static long mod =1000000007L; static long power2 (long a, long b){ long res=1; while (b>0){ if ((b&1)== 1){ res= (res * a % mod)%mod; } a=(a%mod * a%mod)%mod; b=b>>1; } return res; } static boolean []sieveOfEratosthenes(int n){ boolean prime[] = new boolean[n+1]; for(int i=0;i<=n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } return prime; } static void sort(int[] a){ ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sortLong(long[] a){ ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static long gcd (long n, long m){ if (m==0) return n; else return gcd(m, n%m); } static class Pair implements Comparable<Pair>{ int x,y; private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue(); public Pair(int x, int y){ this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pii = (Pair) o; if (x != pii.x) return false; return y == pii.y; } public int hashCode() { return hashMultiplier * x + y; } public int compareTo(Pair o){ if (this.x==o.x) return Integer.compare(this.y,o.y); else return Integer.compare(this.x,o.x); } // this.x-o.x is ascending } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
f1b19638d101a28a9412e92f48560adf
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class c731{ public static void main(String[] args) throws IOException{ BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); int t = sc.nextInt(); for(int o = 0; o<t;o++) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextInt(); } int[][] dp = new int[n+1][n+1]; for(int i = 0 ; i<n;i++) { int cr = 0; for(int j = n-1 ; j>i;j--) { if(arr[i]>arr[j]) { int v = 0; if(i>0) { v = dp[i-1][j]; } cr++; dp[i][j] = cr + v ; }else { int v = 0; if(i>0) { v = dp[i-1][j]; } dp[i][j] = cr + v; } } } long ans = 0; //for(int i = 0 ; i<=n;i++) { // for(int j = 0 ;j<=n;j++) { // System.out.print(dp[i][j] + " "); // } //System.out.println(); //} //System.out.println(); for(int i = 0 ; i<n-1;i++) { for(int j = i + 2; j<n-1;j++) { if(arr[i]<arr[j]) { // System.out.print(i + " " + j + " "); // System.out.println(dp[j-1][j+1] + " " + dp[i][j+1]); ans += dp[j-1][j+1] - dp[i][j+1]; } } } System.out.println(ans); } } //------------------------------------------------------------------------------------------------------------------------------------------------ public static boolean chk(char[] arr , int n) { for(int i = 0 ; i<n;i++) { if(arr[i]>'a') { return false; } } return true; } public static void dfs(HashMap<Integer, ArrayList<Integer>> map, HashSet<Integer> vis , int s, ArrayList<Integer> al ) { if(!vis.contains(s)) { al.add(s); } vis.add(s); if(map.get(s).size() == 0) { StringBuilder sb = new StringBuilder(); sb.append(al.size() + "\n"); for(int z : al) { sb.append(z + " "); } System.out.println(sb); al.clear(); } for(int x : map.get(s)) { if(vis.contains(x)) { continue; } dfs(map, vis, x,al); } } public static ArrayList<Long> printDivisors(long n) { ArrayList<Long> al = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i)al.add(i); else { al.add(i); al.add(n/i); } } } return al; } public static boolean palin(String s) { int n = s.length(); int i = 0; int j = n-1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) { return false; } i++; j--; } return true; } public static boolean check(int[] arr , int n , int v , int l ) { int x = v/2; int y = v/2; // System.out.println(x + " " + y); if(v%2 == 1 ) { x++; } for(int i = 0 ; i<n;i++) { int d = l - arr[i]; int c = Math.min(d/2, y); y -= c; arr[i] -= c*2; if(arr[i] > x) { return false; } x -= arr[i]; } return true; } public static int cnt_set(long x) { long v = 1l; int c =0; int f = 0; while(v<=x) { if((v&x)!=0) { c++; } v = v<<1; } return c; } public static int lis(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(arr[0]); dp[0]= 1; for(int i = 1 ; i<n;i++) { int x = al.get(al.size()-1); if(arr[i]>x) { al.add(arr[i]); }else { int v = lower_bound(al, 0, al.size(), arr[i]); // System.out.println(v); al.set(v, arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } public static int lis2(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(-arr[n-1]); dp[n-1] = 1; // System.out.println(al); for(int i = n-2 ; i>=0;i--) { int x = al.get(al.size()-1); // System.out.println(-arr[i] + " " + i + " " + x); if((-arr[i])>x) { al.add(-arr[i]); }else { int v = lower_bound(al, 0, al.size(), -arr[i]); // System.out.println(v); al.set(v, -arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } public static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { if(r>n) { return 0; } return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //_________________________________________________________________________________________________________________________________________________________________ // private static int[] parent; // private static int[] size; public static int find(int[] parent, int u) { while(u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } private static void union(int[] parent,int[] size,int u, int v) { int rootU = find(parent,u); int rootV = find(parent,v); if(rootU == rootV) { return; } if(size[rootU] < size[rootV]) { parent[rootU] = rootV; size[rootV] += size[rootU]; } else { parent[rootV] = rootU; size[rootU] += size[rootV]; } } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range public static void build(int [] seg,int []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); // seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); // seg[idx] = seg[idx*2+1]+ seg[idx*2+2]; // seg[idx] = Math.min(seg[idx*2+1], seg[idx*2+2]); seg[idx] = seg[idx*2+1] * seg[idx*2+2]; } //for finding minimum in range public static int query(int[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return 1; } int mid = (lo + hi)/2; int left = query(seg,idx*2 +1, lo, mid, l, r); int right = query(seg,idx*2 + 2, mid + 1, hi, l, r); // return Math.min(left, right); //return gcd(left, right); // return Math.min(left, right); return left * right; } // // for sum // //public static void update(int[]seg,int idx, int lo , int hi , int node , int val) { // if(lo == hi) { // seg[idx] += val; // }else { //int mid = (lo + hi )/2; //if(node<=mid && node>=lo) { // update(seg, idx * 2 +1, lo, mid, node, val); //}else { // update(seg, idx*2 + 2, mid + 1, hi, node, val); //} //seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2]; // //} //} //--------------------------------------------------------------------------------------------------------------------------------------- // //static void shuffleArray(int[] ar) //{ // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // int a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } //} // static void shuffleArray(coup[] ar) // { // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // coup a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } // } //----------------------------------------------------------------------------------------------------------------------------------------------------------- } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //------------------------------------------------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------------------- class coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class tripp{ int a; int b; double c; public tripp(int a , int b, double c) { this.a = a; this.b = b; this.c = c; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5745ca87d646d93782cb4949e2b5f610
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
//package codeforces.round789div2; import java.io.*; import java.util.*; import static java.lang.Math.*; public class C { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(); int[] a = in.nextIntArrayPrimitive(n); int[][] ps = new int[n + 1][n]; for(int v = 0; v <= n; v++) { ps[v][0] = a[0] <= v ? 1 : 0; for(int j = 1; j < n; j++) { ps[v][j] = ps[v][j - 1] + (a[j] <= v ? 1 : 0); } } long ans = 0; for(int b = 1; b <= n - 3; b++) { for(int c = b + 1; c <= n - 2; c++) { ans += 1L * ps[a[c] - 1][b - 1] * (ps[a[b] - 1][n - 1] - ps[a[b] - 1][c]); } } out.println(ans); } out.close(); } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
51241ea73cbfbce02ce437a8d1e33390
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); while (t-- > 0) { StringTokenizer st1 = new StringTokenizer(in.readLine()); StringTokenizer st2 = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st1.nextToken()); int[] a = new int[n]; for (int i=0; i<n; i++) { a[i] = Integer.parseInt(st2.nextToken()); } int[][] dp = new int[n][n]; for (int i=0; i<n; i++) { for (int j=0; j<i; j++) { int x = 0; if (a[j] < a[i]) x = 1; if (j-1 >= 0) dp[i][j] = dp[i][j-1] + x; else dp[i][j] = x; } for (int j=n-1; j>i; j--) { int x = 0; if (a[j] < a[i]) x = 1; if (j+1 < n) dp[i][j] = dp[i][j+1] + x; else dp[i][j] = x; } } long ans = 0; for (int i=1; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { int left = dp[j][i-1]; int right = dp[i][j+1]; long count = left * right; ans += count; } } out.println(ans); } in.close(); out.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
6bf20d2b4982120d7c77a2cdc0edd70c
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Map.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.System.*; public class Main { public void tq() throws Exception { st=new StringTokenizer(bq.readLine()); int tq=i(); sb=new StringBuilder(2000000); o: while(tq-->0) { int n=i(); int ar[]=ari(n); int l[][]=new int[n][n]; int ll[][]=new int[n][n]; for(int x=0;x<n;x++)ar[x]--; for(int x=n-1;x>=0;x--) { int c=0; for(int y=n-1;y>=0;y--) { if(ar[y]<x)c++; l[x][y]=c; } } for(int x=n-1;x>=0;x--) { int c=0; for(int y=0;y<n;y++) { if(ar[y]<x)c++; ll[x][y]=c; } } long c=0l; for(int x=1;x<n;x++) { for(int y=x+1;y<n-1;y++) { c+=l[ar[x]][y+1]*ll[ar[y]][x-1]; } } sl(c); } p(sb); } long mod=1000000007l; int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; BufferedReader bq = new BufferedReader(new InputStreamReader(in));StringTokenizer st;StringBuilder sb; public static void main(String[] a)throws Exception{new Main().tq();} int di[][]={{-1,0},{1,0},{0,-1},{0,1}}; int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}}; void f1(int ar[],int v){fill(ar,v);} void f2(int ar[][],int v){for(int a[]:ar)fill(a,v);} void f3(int ar[][][],int v){for(int a[][]:ar)for(int b[]:a)fill(b,v);} void f1(long ar[],long v){fill(ar,v);} void f2(long ar[][],int v){for(long a[]:ar)fill(a,v);} void f3(long ar[][][],int v){for(long a[][]:ar)for(long b[]:a)fill(b,v);} void f(){out.flush();} int p(int i,int p[]){return p[i]<0?i:(p[i]=p(p[i],p));} boolean c(int x,int y,int n,int m){return x>=0&&x<n&&y>=0&&y<m;} int[] so(int ar[]) { Integer r[] = new Integer[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } long[] so(long ar[]) { Long r[] = new Long[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } char[] so(char ar[]) { Character r[] = new Character[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } void p(Object p) {out.print(p);}void pl(Object p) {out.println(p);}void pl() {out.println();} void s(String s) {sb.append(s);} void s(int s) {sb.append(s);} void s(long s) {sb.append(s);} void s(char s) {sb.append(s);} void s(double s) {sb.append(s);} void ss() {sb.append(' ');} void sl(String s) {s(s);sb.append("\n");} void sl(int s) {s(s);sb.append("\n");} void sl(long s) {s(s);sb.append("\n");} void sl(char s) {s(s);sb.append("\n");} void sl(double s) {s(s);sb.append("\n");} void sl() {sb.append("\n");} int l(int v) {return 31 - Integer.numberOfLeadingZeros(v);} long l(long v) {return 63 - Long.numberOfLeadingZeros(v);} int sq(int a) {return (int) sqrt(a);} long sq(long a) {return (long) sqrt(a);} int gcd(int a, int b) { while (b > 0) { int c = a % b; a = b; b = c; } return a; } long gcd(long a, long b) { while (b > 0l) { long c = a % b; a = b; b = c; } return a; } boolean p(String s, int i, int j) { while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; return true; } boolean[] si(int n) { boolean bo[] = new boolean[n + 1]; bo[0] = bo[1] = true; for (int x = 4; x <= n; x += 2) bo[x] = true; for (int x = 3; x * x <= n; x += 2) { if (!bo[x]) { int vv = (x << 1); for (int y = x * x; y <= n; y += vv) bo[y] = true; } } return bo; } long mul(long a, long b, long m) { long r = 1l; a %= m; while (b > 0) { if ((b & 1) == 1) r = (r * a) % m; b >>= 1; a = (a * a) % m; } return r; } int i() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Integer.parseInt(st.nextToken()); } long l() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Long.parseLong(st.nextToken()); } String s() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return st.nextToken(); } double d() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Double.parseDouble(st.nextToken()); } void s(int a[]) { for (int e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(long a[]) { for (long e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(char a[]) { for (char e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(int ar[][]) {for (int a[] : ar) s(a);} void s(long ar[][]) {for (long a[] : ar) s(a);} void s(char ar[][]) {for (char a[] : ar) s(a);} int[] ari(int n) throws IOException { int ar[] = new int[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Integer.parseInt(st.nextToken()); return ar; } long[] arl(int n) throws IOException { long ar[] = new long[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Long.parseLong(st.nextToken()); return ar; } char[] arc(int n) throws IOException { char ar[] = new char[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken().charAt(0); return ar; } double[] ard(int n) throws IOException { double ar[] = new double[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Double.parseDouble(st.nextToken()); return ar; } String[] ars(int n) throws IOException { String ar[] = new String[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken(); return ar; } int[][] ari(int n, int m) throws IOException { int ar[][] = new int[n][m]; for (int x = 0; x < n; x++)ar[x]=ari(m); return ar; } long[][] arl(int n, int m) throws IOException { long ar[][] = new long[n][m]; for (int x = 0; x < n; x++)ar[x]=arl(m); return ar; } char[][] arc(int n, int m) throws IOException { char ar[][] = new char[n][m]; for (int x = 0; x < n; x++)ar[x]=arc(m); return ar; } double[][] ard(int n, int m) throws IOException { double ar[][] = new double[n][m]; for (int x = 0; x < n; x++)ar[x]=ard(m); return ar; } void p(int ar[]) { sb = new StringBuilder(11 * ar.length); for (int a : ar) {sb.append(a);sb.append(' ');} out.println(sb); } void p(long ar[]) { StringBuilder sb = new StringBuilder(20 * ar.length); for (long a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(double ar[]) { StringBuilder sb = new StringBuilder(22 * ar.length); for (double a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(char ar[]) { StringBuilder sb = new StringBuilder(2 * ar.length); for (char aa : ar){sb.append(aa);sb.append(' ');} out.println(sb); } void p(String ar[]) { int c = 0; for (String s : ar) c += s.length() + 1; StringBuilder sb = new StringBuilder(c); for (String a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(int ar[][]) { StringBuilder sb = new StringBuilder(11 * ar.length * ar[0].length); for (int a[] : ar) { for (int aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(long ar[][]) { StringBuilder sb = new StringBuilder(20 * ar.length * ar[0].length); for (long a[] : ar) { for (long aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(double ar[][]) { StringBuilder sb = new StringBuilder(22 * ar.length * ar[0].length); for (double a[] : ar) { for (double aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(char ar[][]) { StringBuilder sb = new StringBuilder(2 * ar.length * ar[0].length); for (char a[] : ar) { for (char aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void pl(Object... ar) {for (Object e : ar) p(e + " ");pl();} }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
24fb2cdd7e18595690f1c078edf5079a
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(in.nextInt(), in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { for (int i = 0; i < testNumber; i++) { int n = in.nextInt(); int[] a = new int[n]; for (int j = 0; j < a.length; j++) { a[j] = in.nextInt(); } out.println(new Solution().solve(a)); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } } class Solution { public long solve(int[] a) { int n = a.length; long sum = 0; long[] ca = new long[n + 1]; for (int i = 1; i < n; i++) { long cd = 0; if (a[n - 1] < a[i]) { cd = 1; } for (int j = a[i - 1] + 1; j < ca.length; j++) { ca[j]++; } for (int j = n - 2; j > i; j--) { sum += ca[a[j]] * cd; if (a[j] < a[i]) { cd++; } } } return sum; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 8
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9a1c3a3fc1163d13cecb81ec7e4e7486
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 01:46:52 09/05/2022 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(); int[] p = in.na(n); long ans = 0; for(int c = 1; c<n; c++) { int[] cnt = new int[n+1]; for(int i = c+1; i<n; i++) cnt[p[i]]++; for(int i = 1; i<=n; i++) cnt[i] += cnt[i-1]; long c1 = 0; for(int b = 0; b<c; b++) { ans += c1*cnt[p[b]]; if(p[b]<p[c]) c1++; } } out.println(ans); } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while(t-->0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a){ int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a){ int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
0722f0cadff76f558b2564c3619a4514
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 01:30:42 09/05/2022 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(); int[] p = in.na(n); long ans = 0; int[][] pre = new int[n][n+1]; int[][] suf = new int[n][n+1]; for(int i = 0; i<n; i++) { if(i>0) for(int j = 0; j<=n; j++) pre[i][j] = pre[i-1][j]; for(int j = p[i]; j<=n; j++) pre[i][j]++; } for(int i = n-1; i>=0; i--) { if(i<n-1) for(int j = 0; j<=n; j++) suf[i][j] = suf[i+1][j]; for(int j = p[i]; j<=n; j++) suf[i][j]++; } for(int b = 1; b<n; b++) { for(int c = b+1; c<n-1; c++) { long c1 = pre[b-1][p[c]-1]; long c2 = suf[c+1][p[b]-1]; ans += c1*c2; } } out.println(ans); } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while(t-->0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a){ int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a){ int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b21caf28714f7cedb0cd3ab1d648e750
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.Arrays; import java.io.*; import java.util.*; import java.util.Random; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /* Solution Created: 19:17:07 08/05/2022 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(); int[] p = in.na(n); Fenwick st = new Fenwick(n + 2); Fenwick st2 = new Fenwick(n + 2); long ans = 0; for (int b = 0; b < n; b++) { st2.clear(); for (int c = b + 1; c < n; c++) st2.add(p[c], 1); for (int c = b + 1; c < n; c++) { st2.add(p[c], -1); long as = st.sum(1, p[c] - 1); long cs = st2.sum(1, p[b] - 1); ans += as * cs; } st.add(p[b], 1); } out.println(ans); } static class Fenwick{ private int[] tree; int n; public Fenwick(int n) { this.n = n; tree = new int[n+1]; } public void clear() { Arrays.fill(tree, 0); } int sum(int r) { int ret = 0; for (; r >= 0; r = (r & (r + 1)) - 1) ret += tree[r]; return ret; } int sum(int l, int r) { return sum(r) - sum(l - 1); } void add(int idx, int delta) { for (; idx < n; idx = idx | (idx + 1)) tree[idx] += delta; } } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while (t-- > 0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util { private static Random random = new Random(); private static long MOD; static long[] fact, inv, invFact; public static void initCombinatorics(int n, long mod, boolean inversesToo, boolean inverseFactorialsToo) { MOD = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i < n + 1; i++) fact[i] = (fact[i - 1] * i) % mod; if (inversesToo) { inv = new long[n + 1]; inv[1] = 1; for (int i = 2; i <= n; ++i) inv[i] = (mod - (mod / i) * inv[(int) (mod % i)] % mod) % mod; } if (inverseFactorialsToo) { invFact = new long[n + 1]; invFact[n] = Util.modInverse(fact[n], mod); for (int i = n - 1; i >= 0; i--) { if (invFact[i + 1] == -1) { invFact[i] = Util.modInverse(fact[i], mod); continue; } invFact[i] = (invFact[i + 1] * (i + 1)) % mod; } } } public static long modInverse(long a, long mod) { long[] gcdE = gcdExtended(a, mod); if (gcdE[0] != 1) return -1; // Inverse doesn't exist long x = gcdE[1]; return (x % mod + mod) % mod; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r) { if (r > n) return 0; return (((fact[n] * invFact[r]) % MOD) * invFact[n - r]) % MOD; } public static long nPr(int n, int r) { if (r > n) return 0; return (fact[n] * invFact[n - r]) % MOD; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n + 1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i * i <= n; i++) if (isPrime[i]) for (int j = i; i * j <= n; j++) isPrime[i * j] = false; return isPrime; } static long pow(long x, long pow, long mod) { long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0) { if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while (b != 0) { tmp = b; b = a % b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while (b != 0) { tmp = b; b = a % b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max - min + 1) + min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { int tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length - 1); } public static void reverse(long[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { long tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length - 1); } public static void reverse(float[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { float tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length - 1); } public static void reverse(double[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { double tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length - 1); } public static void reverse(char[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { char tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length - 1); } public static <T> void reverse(T[] s, int l, int r) { for (int i = l; i <= (l + r) / 2; i++) { T tmp = s[i]; s[i] = s[r + l - i]; s[r + l - i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length - 1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a) { int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ans[m - j - 1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a) { int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ans[m - j - 1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
39b623681e5d0e222b0838f3fce104ce
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/*----------- ---------------* Author : Ryan Ranaut __Hope is a big word, never lose it__ ------------- --------------*/ import java.io.*; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); static final int mod = 1_000_000_007; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } /*--------------------------------------------------------------------------*/ //Try seeing general case //Minimization Maximization - BS..... Connections - Graphs..... //Greedy not worthy - Try DP //Think edge cases public static void main(String[] args) { FastReader s = new FastReader(); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); int[] a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = s.nextInt(); out.println(find(n, a)); } out.close(); } public static long find(int n, int[] a) { int[][] ca = new int[n+1][n+1];//c>a int[][] bd = new int[n+2][n+2];//b>d for(int i=1;i<=n;i++) { for(int j=1;j<i;j++) { if(a[i]>a[j]) ca[i][j]++; ca[i][j] += ca[i][j-1]; } } for(int i=1;i<=n;i++) { for(int j=n;j>i;j--) { if(a[i]>a[j]) bd[i][j]++; bd[i][j] += bd[i][j+1]; } } long res = 0; for(int b=1;b<=n;b++) { for(int c=b+1;c<=n;c++) res += ((long) ca[c][b - 1] * bd[b][c + 1]); } return res; } /*----------------------------------End of the road--------------------------------------*/ static class DSU { int[] parent; int[] ranks; int[] groupSize; int size; public DSU(int n) { size = n; parent = new int[n];//0 based ranks = new int[n]; groupSize = new int[n];//Size of each component for (int i = 0; i < n; i++) { parent[i] = i; ranks[i] = 1; groupSize[i] = 1; } } public int find(int x)//Path Compression { if (parent[x] == x) return x; else return parent[x] = find(parent[x]); } public void union(int x, int y)//Union by rank { int x_rep = find(x); int y_rep = find(y); if (x_rep == y_rep) return; if (ranks[x_rep] < ranks[y_rep]) { parent[x_rep] = y_rep; groupSize[y_rep] += groupSize[x_rep]; } else if (ranks[x_rep] > ranks[y_rep]) { parent[y_rep] = x_rep; groupSize[x_rep] += groupSize[y_rep]; } else { parent[y_rep] = x_rep; ranks[x_rep]++; groupSize[x_rep] += groupSize[y_rep]; } size--;//Total connected components } } public static int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); } public static long gcd(long x, long y) { return y == 0L ? x : gcd(y, x % y); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long pow(long a, long b) { if (b == 0L) return 1L; long tmp = 1; while (b > 1L) { if ((b & 1L) == 1) tmp *= a; a *= a; b >>= 1; } return (tmp * a); } public static long modPow(long a, long b, long mod) { if (b == 0L) return 1L; long tmp = 1; while (b > 1L) { if ((b & 1L) == 1L) tmp *= a; a *= a; a %= mod; tmp %= mod; b >>= 1; } return (tmp * a) % mod; } static long mul(long a, long b) { return a * b; } static long fact(int n) { long ans = 1; for (int i = 2; i <= n; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int... a) { for (int x : a) out.print(x + " "); out.println(); } static void debug(long... a) { for (long x : a) out.print(x + " "); out.println(); } static void debugMatrix(int[][] a) { for (int[] x : a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for (long[] x : a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for (int x : a) ls.add(x); Collections.sort(ls); for (int i = 0; i < a.length; i++) a[i] = ls.get(i); } static void sort(long[] a) { ArrayList<Long> ls = new ArrayList<>(); for (long x : a) ls.add(x); Collections.sort(ls); for (int i = 0; i < a.length; i++) a[i] = ls.get(i); } static class Pair { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5670088112061ccb16c2953957d035e0
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/*----------- ---------------* Author : Ryan Ranaut __Hope is a big word, never lose it__ ------------- --------------*/ import java.io.*; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); static final int mod = 1_000_000_007; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } /*--------------------------------------------------------------------------*/ //Try seeing general case //Minimization Maximization - BS..... Connections - Graphs..... //Greedy not worthy - Try DP //Think edge cases public static void main(String[] args) { FastReader s = new FastReader(); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); int[] a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = s.nextInt(); out.println(find(n, a)); } out.close(); } public static long find(int n, int[] a) { int[][] ca = new int[n+1][n+1];//c>a int[][] bd = new int[n+2][n+2];//b>d for(int i=1;i<=n;i++) { for(int j=1;j<i;j++) { if(a[i]>a[j]) ca[i][j]++; ca[i][j] += ca[i][j-1]; } } for(int i=1;i<=n;i++) { for(int j=n;j>i;j--) { if(a[i]>a[j]) bd[i][j]++; bd[i][j] += bd[i][j+1]; } } long res = 0; for(int b=1;b<=n;b++) { for(int c=b+1;c<=n;c++) res += ((long) ca[c][b - 1] * bd[b][c + 1]); } return res; } /*----------------------------------End of the road--------------------------------------*/ static class DSU { int[] parent; int[] ranks; int[] groupSize; int size; public DSU(int n) { size = n; parent = new int[n];//0 based ranks = new int[n]; groupSize = new int[n];//Size of each component for (int i = 0; i < n; i++) { parent[i] = i; ranks[i] = 1; groupSize[i] = 1; } } public int find(int x)//Path Compression { if (parent[x] == x) return x; else return parent[x] = find(parent[x]); } public void union(int x, int y)//Union by rank { int x_rep = find(x); int y_rep = find(y); if (x_rep == y_rep) return; if (ranks[x_rep] < ranks[y_rep]) { parent[x_rep] = y_rep; groupSize[y_rep] += groupSize[x_rep]; } else if (ranks[x_rep] > ranks[y_rep]) { parent[y_rep] = x_rep; groupSize[x_rep] += groupSize[y_rep]; } else { parent[y_rep] = x_rep; ranks[x_rep]++; groupSize[x_rep] += groupSize[y_rep]; } size--;//Total connected components } } public static int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); } public static long gcd(long x, long y) { return y == 0L ? x : gcd(y, x % y); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long pow(long a, long b) { if (b == 0L) return 1L; long tmp = 1; while (b > 1L) { if ((b & 1L) == 1) tmp *= a; a *= a; b >>= 1; } return (tmp * a); } public static long modPow(long a, long b, long mod) { if (b == 0L) return 1L; long tmp = 1; while (b > 1L) { if ((b & 1L) == 1L) tmp *= a; a *= a; a %= mod; tmp %= mod; b >>= 1; } return (tmp * a) % mod; } static long mul(long a, long b) { return a * b; } static long fact(int n) { long ans = 1; for (int i = 2; i <= n; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int... a) { for (int x : a) out.print(x + " "); out.println(); } static void debug(long... a) { for (long x : a) out.print(x + " "); out.println(); } static void debugMatrix(int[][] a) { for (int[] x : a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for (long[] x : a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for (int x : a) ls.add(x); Collections.sort(ls); for (int i = 0; i < a.length; i++) a[i] = ls.get(i); } static void sort(long[] a) { ArrayList<Long> ls = new ArrayList<>(); for (long x : a) ls.add(x); Collections.sort(ls); for (int i = 0; i < a.length; i++) a[i] = ls.get(i); } static class Pair { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
4bcc038724877120779ddb2bb167e408
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; /** * * @author eslam */ public class IceCave { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // Beginning of the solution static FastReader input = new FastReader(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Long>> powerSet = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static boolean ca = true; static int dp[]; public static void main(String[] args) throws IOException { int t = input.nextInt(); while (t-- > 0) { int n = input.nextInt(); int a[] = new int[n]; long fans = 0; for (int i = 0; i < n; i++) { a[i] = input.nextInt() - 1; } long ans[][] = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { ans[a[i]][j] = 1; } } } for (int i = 0; i < n; i++) { suffixSum(ans[i]); } for (int i = 0; i < n - 1; i++) { int b = 0; for (int j = 0; j < i; j++) { long an = ans[a[j]][i + 1]; fans += (b) * an; if (a[j] < a[i]) { b++; } } } log.write(fans + "\n"); } log.flush(); } public static void graphRepresintionWithCycle(ArrayList<Integer>[] a, int q) { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static void dfsRecursive(int n, ArrayList<Integer>[] a, boolean visited[]) { ArrayList<Integer> nodes = a[n]; visited[n] = true; for (Integer node : nodes) { if (!visited[node]) { dfsRecursive(node, a, visited); } } } public static int get(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } public static int primeFactors(int n) { int sum = 0; while (n % 2 == 0) { sum += 2; n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { sum += get(i); n /= i; } if (n < i) { break; } } if (n > 2) { sum += get(n); } return sum; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } public static void genrate(int ind, long[] a, ArrayList<Long> sub) { if (ind == a.length) { powerSet.add(sub); return; } ArrayList<Long> have = new ArrayList<>(); ArrayList<Long> less = new ArrayList<>(); for (int i = 0; i < sub.size(); i++) { have.add(sub.get(i)); less.add(sub.get(i)); } have.add(a[ind]); genrate(ind + 1, a, have); genrate(ind + 1, a, less); } // end of solution public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n *= t; t--; } return n; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void print(int a[]) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class pair { long x; int y; public pair(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(long a, long b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } /** */ // class RedBlackNode static class RedBlackNode<T extends Comparable<T>> { /** * Possible color for this node */ public static final int BLACK = 0; /** * Possible color for this node */ public static final int RED = 1; // the key of each node public T key; /** * Parent of node */ RedBlackNode<T> parent; /** * Left child */ RedBlackNode<T> left; /** * Right child */ RedBlackNode<T> right; // the number of elements to the left of each node public int numLeft = 0; // the number of elements to the right of each node public int numRight = 0; // the color of a node public int color; RedBlackNode() { color = BLACK; numLeft = 0; numRight = 0; parent = null; left = null; right = null; } // Constructor which sets key to the argument. RedBlackNode(T key) { this(); this.key = key; } }// end class RedBlackNode static class RedBlackTree<T extends Comparable<T>> { // Root initialized to nil. private RedBlackNode<T> nil = new RedBlackNode<T>(); private RedBlackNode<T> root = nil; public RedBlackTree() { root.left = nil; root.right = nil; root.parent = nil; } // @param: x, The node which the lefRotate is to be performed on. // Performs a leftRotate around x. private void leftRotate(RedBlackNode<T> x) { // Call leftRotateFixup() which updates the numLeft // and numRight values. leftRotateFixup(x); // Perform the left rotate as described in the algorithm // in the course text. RedBlackNode<T> y; y = x.right; x.right = y.left; // Check for existence of y.left and make pointer changes if (!isNil(y.left)) { y.left.parent = x; } y.parent = x.parent; // x's parent is nul if (isNil(x.parent)) { root = y; } // x is the left child of it's parent else if (x.parent.left == x) { x.parent.left = y; } // x is the right child of it's parent. else { x.parent.right = y; } // Finish of the leftRotate y.left = x; x.parent = y; }// end leftRotate(RedBlackNode x) // @param: x, The node which the leftRotate is to be performed on. // Updates the numLeft & numRight values affected by leftRotate. private void leftRotateFixup(RedBlackNode x) { // Case 1: Only x, x.right and x.right.right always are not nil. if (isNil(x.left) && isNil(x.right.left)) { x.numLeft = 0; x.numRight = 0; x.right.numLeft = 1; } // Case 2: x.right.left also exists in addition to Case 1 else if (isNil(x.left) && !isNil(x.right.left)) { x.numLeft = 0; x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 2 + x.right.left.numLeft + x.right.left.numRight; } // Case 3: x.left also exists in addition to Case 1 else if (!isNil(x.left) && isNil(x.right.left)) { x.numRight = 0; x.right.numLeft = 2 + x.left.numLeft + x.left.numRight; } // Case 4: x.left and x.right.left both exist in addtion to Case 1 else { x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 3 + x.left.numLeft + x.left.numRight + x.right.left.numLeft + x.right.left.numRight; } }// end leftRotateFixup(RedBlackNode x) // @param: x, The node which the rightRotate is to be performed on. // Updates the numLeft and numRight values affected by the Rotate. private void rightRotate(RedBlackNode<T> y) { // Call rightRotateFixup to adjust numRight and numLeft values rightRotateFixup(y); // Perform the rotate as described in the course text. RedBlackNode<T> x = y.left; y.left = x.right; // Check for existence of x.right if (!isNil(x.right)) { x.right.parent = y; } x.parent = y.parent; // y.parent is nil if (isNil(y.parent)) { root = x; } // y is a right child of it's parent. else if (y.parent.right == y) { y.parent.right = x; } // y is a left child of it's parent. else { y.parent.left = x; } x.right = y; y.parent = x; }// end rightRotate(RedBlackNode y) // @param: y, the node around which the righRotate is to be performed. // Updates the numLeft and numRight values affected by the rotate private void rightRotateFixup(RedBlackNode y) { // Case 1: Only y, y.left and y.left.left exists. if (isNil(y.right) && isNil(y.left.right)) { y.numRight = 0; y.numLeft = 0; y.left.numRight = 1; } // Case 2: y.left.right also exists in addition to Case 1 else if (isNil(y.right) && !isNil(y.left.right)) { y.numRight = 0; y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 2 + y.left.right.numRight + y.left.right.numLeft; } // Case 3: y.right also exists in addition to Case 1 else if (!isNil(y.right) && isNil(y.left.right)) { y.numLeft = 0; y.left.numRight = 2 + y.right.numRight + y.right.numLeft; } // Case 4: y.right & y.left.right exist in addition to Case 1 else { y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 3 + y.right.numRight + y.right.numLeft + y.left.right.numRight + y.left.right.numLeft; } }// end rightRotateFixup(RedBlackNode y) public void insert(T key) { insert(new RedBlackNode<T>(key)); } // @param: z, the node to be inserted into the Tree rooted at root // Inserts z into the appropriate position in the RedBlackTree while // updating numLeft and numRight values. private void insert(RedBlackNode<T> z) { // Create a reference to root & initialize a node to nil RedBlackNode<T> y = nil; RedBlackNode<T> x = root; // While we haven't reached a the end of the tree keep // tryint to figure out where z should go while (!isNil(x)) { y = x; // if z.key is < than the current key, go left if (z.key.compareTo(x.key) < 0) { // Update x.numLeft as z is < than x x.numLeft++; x = x.left; } // else z.key >= x.key so go right. else { // Update x.numGreater as z is => x x.numRight++; x = x.right; } } // y will hold z's parent z.parent = y; // Depending on the value of y.key, put z as the left or // right child of y if (isNil(y)) { root = z; } else if (z.key.compareTo(y.key) < 0) { y.left = z; } else { y.right = z; } // Initialize z's children to nil and z's color to red z.left = nil; z.right = nil; z.color = RedBlackNode.RED; // Call insertFixup(z) insertFixup(z); }// end insert(RedBlackNode z) // @param: z, the node which was inserted and may have caused a violation // of the RedBlackTree properties // Fixes up the violation of the RedBlackTree properties that may have // been caused during insert(z) private void insertFixup(RedBlackNode<T> z) { RedBlackNode<T> y = nil; // While there is a violation of the RedBlackTree properties.. while (z.parent.color == RedBlackNode.RED) { // If z's parent is the the left child of it's parent. if (z.parent == z.parent.parent.left) { // Initialize y to z 's cousin y = z.parent.parent.right; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black & z is a right child else if (z == z.parent.right) { // leftRotaet around z's parent z = z.parent; leftRotate(z); } // Case 3: else y is black & z is a left child else { // recolor and rotate round z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; rightRotate(z.parent.parent); } } // If z's parent is the right child of it's parent. else { // Initialize y to z's cousin y = z.parent.parent.left; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black and z is a left child else if (z == z.parent.left) { // rightRotate around z's parent z = z.parent; rightRotate(z); } // Case 3: if y is black and z is a right child else { // recolor and rotate around z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; leftRotate(z.parent.parent); } } } // Color root black at all times root.color = RedBlackNode.BLACK; }// end insertFixup(RedBlackNode z) // @param: node, a RedBlackNode // @param: node, the node with the smallest key rooted at node public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) { // while there is a smaller key, keep going left while (!isNil(node.left)) { node = node.left; } return node; }// end treeMinimum(RedBlackNode node) // @param: x, a RedBlackNode whose successor we must find // @return: return's the node the with the next largest key // from x.key public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) { // if x.left is not nil, call treeMinimum(x.right) and // return it's value if (!isNil(x.left)) { return treeMinimum(x.right); } RedBlackNode<T> y = x.parent; // while x is it's parent's right child... while (!isNil(y) && x == y.right) { // Keep moving up in the tree x = y; y = y.parent; } // Return successor return y; }// end treeMinimum(RedBlackNode x) // @param: z, the RedBlackNode which is to be removed from the the tree // Remove's z from the RedBlackTree rooted at root public void remove(RedBlackNode<T> v) { RedBlackNode<T> z = search(v.key); // Declare variables RedBlackNode<T> x = nil; RedBlackNode<T> y = nil; // if either one of z's children is nil, then we must remove z if (isNil(z.left) || isNil(z.right)) { y = z; } // else we must remove the successor of z else { y = treeSuccessor(z); } // Let x be the left or right child of y (y can only have one child) if (!isNil(y.left)) { x = y.left; } else { x = y.right; } // link x's parent to y's parent x.parent = y.parent; // If y's parent is nil, then x is the root if (isNil(y.parent)) { root = x; } // else if y is a left child, set x to be y's left sibling else if (!isNil(y.parent.left) && y.parent.left == y) { y.parent.left = x; } // else if y is a right child, set x to be y's right sibling else if (!isNil(y.parent.right) && y.parent.right == y) { y.parent.right = x; } // if y != z, trasfer y's satellite data into z. if (y != z) { z.key = y.key; } // Update the numLeft and numRight numbers which might need // updating due to the deletion of z.key. fixNodeData(x, y); // If y's color is black, it is a violation of the // RedBlackTree properties so call removeFixup() if (y.color == RedBlackNode.BLACK) { removeFixup(x); } }// end remove(RedBlackNode z) // @param: y, the RedBlackNode which was actually deleted from the tree // @param: key, the value of the key that used to be in y private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) { // Initialize two variables which will help us traverse the tree RedBlackNode<T> current = nil; RedBlackNode<T> track = nil; // if x is nil, then we will start updating at y.parent // Set track to y, y.parent's child if (isNil(x)) { current = y.parent; track = y; } // if x is not nil, then we start updating at x.parent // Set track to x, x.parent's child else { current = x.parent; track = x; } // while we haven't reached the root while (!isNil(current)) { // if the node we deleted has a different key than // the current node if (y.key != current.key) { // if the node we deleted is greater than // current.key then decrement current.numRight if (y.key.compareTo(current.key) > 0) { current.numRight--; } // if the node we deleted is less than // current.key thendecrement current.numLeft if (y.key.compareTo(current.key) < 0) { current.numLeft--; } } // if the node we deleted has the same key as the // current node we are checking else { // the cases where the current node has any nil // children and update appropriately if (isNil(current.left)) { current.numLeft--; } else if (isNil(current.right)) { current.numRight--; } // the cases where current has two children and // we must determine whether track is it's left // or right child and update appropriately else if (track == current.right) { current.numRight--; } else if (track == current.left) { current.numLeft--; } } // update track and current track = current; current = current.parent; } }//end fixNodeData() // @param: x, the child of the deleted node from remove(RedBlackNode v) // Restores the Red Black properties that may have been violated during // the removal of a node in remove(RedBlackNode v) private void removeFixup(RedBlackNode<T> x) { RedBlackNode<T> w; // While we haven't fixed the tree completely... while (x != root && x.color == RedBlackNode.BLACK) { // if x is it's parent's left child if (x == x.parent.left) { // set w = x's sibling w = x.parent.right; // Case 1, w's color is red. if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; leftRotate(x.parent); w = x.parent.right; } // Case 2, both of w's children are black if (w.left.color == RedBlackNode.BLACK && w.right.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's right child is black if (w.right.color == RedBlackNode.BLACK) { w.left.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; rightRotate(w); w = x.parent.right; } // Case 4, w = black, w.right = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.right.color = RedBlackNode.BLACK; leftRotate(x.parent); x = root; } } // if x is it's parent's right child else { // set w to x's sibling w = x.parent.left; // Case 1, w's color is red if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; rightRotate(x.parent); w = x.parent.left; } // Case 2, both of w's children are black if (w.right.color == RedBlackNode.BLACK && w.left.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's left child is black if (w.left.color == RedBlackNode.BLACK) { w.right.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; leftRotate(w); w = x.parent.left; } // Case 4, w = black, and w.left = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.left.color = RedBlackNode.BLACK; rightRotate(x.parent); x = root; } } }// end while // set x to black to ensure there is no violation of // RedBlack tree Properties x.color = RedBlackNode.BLACK; }// end removeFixup(RedBlackNode x) // @param: key, the key whose node we want to search for // @return: returns a node with the key, key, if not found, returns null // Searches for a node with key k and returns the first such node, if no // such node is found returns null public RedBlackNode<T> search(T key) { // Initialize a pointer to the root to traverse the tree RedBlackNode<T> current = root; // While we haven't reached the end of the tree while (!isNil(current)) { // If we have found a node with a key equal to key if (current.key.equals(key)) // return that node and exit search(int) { return current; } // go left or right based on value of current and key else if (current.key.compareTo(key) < 0) { current = current.right; } // go left or right based on value of current and key else { current = current.left; } } // we have not found a node whose key is "key" return null; }// end search(int key) // @param: key, any Comparable object // @return: return's the number of elements greater than key public int numGreater(T key) { // Call findNumGreater(root, key) which will return the number // of nodes whose key is greater than key return findNumGreater(root, key); }// end numGreater(int key) // @param: key, any Comparable object // @return: return's teh number of elements smaller than key public int numSmaller(T key) { // Call findNumSmaller(root,key) which will return // the number of nodes whose key is greater than key return findNumSmaller(root, key); }// end numSmaller(int key) // @param: node, the root of the tree, the key who we must // compare other node key's to. // @return: the number of nodes greater than key. public int findNumGreater(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, all elements right of node are // greater than key, add this to our total and look to the left else if (key.compareTo(node.key) < 0) { return 1 + node.numRight + findNumGreater(node.left, key); } // If key is greater than node.key, then look to the right as // all elements to the left of node are smaller than key else { return findNumGreater(node.right, key); } }// end findNumGreater(RedBlackNode, int key) /** * Returns sorted list of keys greater than key. Size of list will not * exceed maxReturned * * @param key Key to search for * @param maxReturned Maximum number of results to return * @return List of keys greater than key. List may not exceed * maxReturned */ public List<T> getGreaterThan(T key, Integer maxReturned) { List<T> list = new ArrayList<T>(); getGreaterThan(root, key, list); return list.subList(0, Math.min(maxReturned, list.size())); } private void getGreaterThan(RedBlackNode<T> node, T key, List<T> list) { if (isNil(node)) { return; } else if (node.key.compareTo(key) > 0) { getGreaterThan(node.left, key, list); list.add(node.key); getGreaterThan(node.right, key, list); } else { getGreaterThan(node.right, key, list); } } // @param: node, the root of the tree, the key who we must compare other // node key's to. // @return: the number of nodes smaller than key. public int findNumSmaller(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, look to the left as all // elements on the right of node are greater than key else if (key.compareTo(node.key) <= 0) { return findNumSmaller(node.left, key); } // If key is larger than node.key, all elements to the left of // node are smaller than key, add this to our total and look // to the right. else { return 1 + node.numLeft + findNumSmaller(node.right, key); } }// end findNumSmaller(RedBlackNode nod, int key) // @param: node, the RedBlackNode we must check to see whether it's nil // @return: return's true of node is nil and false otherwise private boolean isNil(RedBlackNode node) { // return appropriate value return node == nil; }// end isNil(RedBlackNode node) // @return: return's the size of the tree // Return's the # of nodes including the root which the RedBlackTree // rooted at root has. public int size() { // Return the number of nodes to the root's left + the number of // nodes on the root's right + the root itself. return root.numLeft + root.numRight + 1; }// end size() }// end class RedBlackTree }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
17d84ec4ab9a0f523c83577c803c154f
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; /** * * @author eslam */ public class IceCave { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // Beginning of the solution static FastReader input = new FastReader(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Long>> powerSet = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static boolean ca = true; static int dp[]; public static void main(String[] args) throws IOException { int t = input.nextInt(); while (t-- > 0) { int n = input.nextInt(); int a[] = new int[n]; long fans = 0; for (int i = 0; i < n; i++) { a[i] = input.nextInt()-1; } int ans[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { ans[a[i]][j] = 1; } } } for (int i = 0; i < n; i++) { suffixSum(ans[i]); } for (int i = 0; i < n-1; i++) { int b = 0; for (int j = 0; j < i; j++) { long an = ans[a[j]][i+1]; fans += (b) * an; if (a[j] < a[i]) { b++; } } } log.write(fans + "\n"); } log.flush(); } public static void graphRepresintionWithCycle(ArrayList<Integer>[] a, int q) { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static void dfsRecursive(int n, ArrayList<Integer>[] a, boolean visited[]) { ArrayList<Integer> nodes = a[n]; visited[n] = true; for (Integer node : nodes) { if (!visited[node]) { dfsRecursive(node, a, visited); } } } public static int get(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } public static int primeFactors(int n) { int sum = 0; while (n % 2 == 0) { sum += 2; n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { sum += get(i); n /= i; } if (n < i) { break; } } if (n > 2) { sum += get(n); } return sum; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } public static void genrate(int ind, long[] a, ArrayList<Long> sub) { if (ind == a.length) { powerSet.add(sub); return; } ArrayList<Long> have = new ArrayList<>(); ArrayList<Long> less = new ArrayList<>(); for (int i = 0; i < sub.size(); i++) { have.add(sub.get(i)); less.add(sub.get(i)); } have.add(a[ind]); genrate(ind + 1, a, have); genrate(ind + 1, a, less); } // end of solution public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n *= t; t--; } return n; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(int[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void print(int a[]) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class pair { long x; int y; public pair(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(long a, long b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } /** */ // class RedBlackNode static class RedBlackNode<T extends Comparable<T>> { /** * Possible color for this node */ public static final int BLACK = 0; /** * Possible color for this node */ public static final int RED = 1; // the key of each node public T key; /** * Parent of node */ RedBlackNode<T> parent; /** * Left child */ RedBlackNode<T> left; /** * Right child */ RedBlackNode<T> right; // the number of elements to the left of each node public int numLeft = 0; // the number of elements to the right of each node public int numRight = 0; // the color of a node public int color; RedBlackNode() { color = BLACK; numLeft = 0; numRight = 0; parent = null; left = null; right = null; } // Constructor which sets key to the argument. RedBlackNode(T key) { this(); this.key = key; } }// end class RedBlackNode static class RedBlackTree<T extends Comparable<T>> { // Root initialized to nil. private RedBlackNode<T> nil = new RedBlackNode<T>(); private RedBlackNode<T> root = nil; public RedBlackTree() { root.left = nil; root.right = nil; root.parent = nil; } // @param: x, The node which the lefRotate is to be performed on. // Performs a leftRotate around x. private void leftRotate(RedBlackNode<T> x) { // Call leftRotateFixup() which updates the numLeft // and numRight values. leftRotateFixup(x); // Perform the left rotate as described in the algorithm // in the course text. RedBlackNode<T> y; y = x.right; x.right = y.left; // Check for existence of y.left and make pointer changes if (!isNil(y.left)) { y.left.parent = x; } y.parent = x.parent; // x's parent is nul if (isNil(x.parent)) { root = y; } // x is the left child of it's parent else if (x.parent.left == x) { x.parent.left = y; } // x is the right child of it's parent. else { x.parent.right = y; } // Finish of the leftRotate y.left = x; x.parent = y; }// end leftRotate(RedBlackNode x) // @param: x, The node which the leftRotate is to be performed on. // Updates the numLeft & numRight values affected by leftRotate. private void leftRotateFixup(RedBlackNode x) { // Case 1: Only x, x.right and x.right.right always are not nil. if (isNil(x.left) && isNil(x.right.left)) { x.numLeft = 0; x.numRight = 0; x.right.numLeft = 1; } // Case 2: x.right.left also exists in addition to Case 1 else if (isNil(x.left) && !isNil(x.right.left)) { x.numLeft = 0; x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 2 + x.right.left.numLeft + x.right.left.numRight; } // Case 3: x.left also exists in addition to Case 1 else if (!isNil(x.left) && isNil(x.right.left)) { x.numRight = 0; x.right.numLeft = 2 + x.left.numLeft + x.left.numRight; } // Case 4: x.left and x.right.left both exist in addtion to Case 1 else { x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 3 + x.left.numLeft + x.left.numRight + x.right.left.numLeft + x.right.left.numRight; } }// end leftRotateFixup(RedBlackNode x) // @param: x, The node which the rightRotate is to be performed on. // Updates the numLeft and numRight values affected by the Rotate. private void rightRotate(RedBlackNode<T> y) { // Call rightRotateFixup to adjust numRight and numLeft values rightRotateFixup(y); // Perform the rotate as described in the course text. RedBlackNode<T> x = y.left; y.left = x.right; // Check for existence of x.right if (!isNil(x.right)) { x.right.parent = y; } x.parent = y.parent; // y.parent is nil if (isNil(y.parent)) { root = x; } // y is a right child of it's parent. else if (y.parent.right == y) { y.parent.right = x; } // y is a left child of it's parent. else { y.parent.left = x; } x.right = y; y.parent = x; }// end rightRotate(RedBlackNode y) // @param: y, the node around which the righRotate is to be performed. // Updates the numLeft and numRight values affected by the rotate private void rightRotateFixup(RedBlackNode y) { // Case 1: Only y, y.left and y.left.left exists. if (isNil(y.right) && isNil(y.left.right)) { y.numRight = 0; y.numLeft = 0; y.left.numRight = 1; } // Case 2: y.left.right also exists in addition to Case 1 else if (isNil(y.right) && !isNil(y.left.right)) { y.numRight = 0; y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 2 + y.left.right.numRight + y.left.right.numLeft; } // Case 3: y.right also exists in addition to Case 1 else if (!isNil(y.right) && isNil(y.left.right)) { y.numLeft = 0; y.left.numRight = 2 + y.right.numRight + y.right.numLeft; } // Case 4: y.right & y.left.right exist in addition to Case 1 else { y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 3 + y.right.numRight + y.right.numLeft + y.left.right.numRight + y.left.right.numLeft; } }// end rightRotateFixup(RedBlackNode y) public void insert(T key) { insert(new RedBlackNode<T>(key)); } // @param: z, the node to be inserted into the Tree rooted at root // Inserts z into the appropriate position in the RedBlackTree while // updating numLeft and numRight values. private void insert(RedBlackNode<T> z) { // Create a reference to root & initialize a node to nil RedBlackNode<T> y = nil; RedBlackNode<T> x = root; // While we haven't reached a the end of the tree keep // tryint to figure out where z should go while (!isNil(x)) { y = x; // if z.key is < than the current key, go left if (z.key.compareTo(x.key) < 0) { // Update x.numLeft as z is < than x x.numLeft++; x = x.left; } // else z.key >= x.key so go right. else { // Update x.numGreater as z is => x x.numRight++; x = x.right; } } // y will hold z's parent z.parent = y; // Depending on the value of y.key, put z as the left or // right child of y if (isNil(y)) { root = z; } else if (z.key.compareTo(y.key) < 0) { y.left = z; } else { y.right = z; } // Initialize z's children to nil and z's color to red z.left = nil; z.right = nil; z.color = RedBlackNode.RED; // Call insertFixup(z) insertFixup(z); }// end insert(RedBlackNode z) // @param: z, the node which was inserted and may have caused a violation // of the RedBlackTree properties // Fixes up the violation of the RedBlackTree properties that may have // been caused during insert(z) private void insertFixup(RedBlackNode<T> z) { RedBlackNode<T> y = nil; // While there is a violation of the RedBlackTree properties.. while (z.parent.color == RedBlackNode.RED) { // If z's parent is the the left child of it's parent. if (z.parent == z.parent.parent.left) { // Initialize y to z 's cousin y = z.parent.parent.right; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black & z is a right child else if (z == z.parent.right) { // leftRotaet around z's parent z = z.parent; leftRotate(z); } // Case 3: else y is black & z is a left child else { // recolor and rotate round z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; rightRotate(z.parent.parent); } } // If z's parent is the right child of it's parent. else { // Initialize y to z's cousin y = z.parent.parent.left; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black and z is a left child else if (z == z.parent.left) { // rightRotate around z's parent z = z.parent; rightRotate(z); } // Case 3: if y is black and z is a right child else { // recolor and rotate around z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; leftRotate(z.parent.parent); } } } // Color root black at all times root.color = RedBlackNode.BLACK; }// end insertFixup(RedBlackNode z) // @param: node, a RedBlackNode // @param: node, the node with the smallest key rooted at node public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) { // while there is a smaller key, keep going left while (!isNil(node.left)) { node = node.left; } return node; }// end treeMinimum(RedBlackNode node) // @param: x, a RedBlackNode whose successor we must find // @return: return's the node the with the next largest key // from x.key public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) { // if x.left is not nil, call treeMinimum(x.right) and // return it's value if (!isNil(x.left)) { return treeMinimum(x.right); } RedBlackNode<T> y = x.parent; // while x is it's parent's right child... while (!isNil(y) && x == y.right) { // Keep moving up in the tree x = y; y = y.parent; } // Return successor return y; }// end treeMinimum(RedBlackNode x) // @param: z, the RedBlackNode which is to be removed from the the tree // Remove's z from the RedBlackTree rooted at root public void remove(RedBlackNode<T> v) { RedBlackNode<T> z = search(v.key); // Declare variables RedBlackNode<T> x = nil; RedBlackNode<T> y = nil; // if either one of z's children is nil, then we must remove z if (isNil(z.left) || isNil(z.right)) { y = z; } // else we must remove the successor of z else { y = treeSuccessor(z); } // Let x be the left or right child of y (y can only have one child) if (!isNil(y.left)) { x = y.left; } else { x = y.right; } // link x's parent to y's parent x.parent = y.parent; // If y's parent is nil, then x is the root if (isNil(y.parent)) { root = x; } // else if y is a left child, set x to be y's left sibling else if (!isNil(y.parent.left) && y.parent.left == y) { y.parent.left = x; } // else if y is a right child, set x to be y's right sibling else if (!isNil(y.parent.right) && y.parent.right == y) { y.parent.right = x; } // if y != z, trasfer y's satellite data into z. if (y != z) { z.key = y.key; } // Update the numLeft and numRight numbers which might need // updating due to the deletion of z.key. fixNodeData(x, y); // If y's color is black, it is a violation of the // RedBlackTree properties so call removeFixup() if (y.color == RedBlackNode.BLACK) { removeFixup(x); } }// end remove(RedBlackNode z) // @param: y, the RedBlackNode which was actually deleted from the tree // @param: key, the value of the key that used to be in y private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) { // Initialize two variables which will help us traverse the tree RedBlackNode<T> current = nil; RedBlackNode<T> track = nil; // if x is nil, then we will start updating at y.parent // Set track to y, y.parent's child if (isNil(x)) { current = y.parent; track = y; } // if x is not nil, then we start updating at x.parent // Set track to x, x.parent's child else { current = x.parent; track = x; } // while we haven't reached the root while (!isNil(current)) { // if the node we deleted has a different key than // the current node if (y.key != current.key) { // if the node we deleted is greater than // current.key then decrement current.numRight if (y.key.compareTo(current.key) > 0) { current.numRight--; } // if the node we deleted is less than // current.key thendecrement current.numLeft if (y.key.compareTo(current.key) < 0) { current.numLeft--; } } // if the node we deleted has the same key as the // current node we are checking else { // the cases where the current node has any nil // children and update appropriately if (isNil(current.left)) { current.numLeft--; } else if (isNil(current.right)) { current.numRight--; } // the cases where current has two children and // we must determine whether track is it's left // or right child and update appropriately else if (track == current.right) { current.numRight--; } else if (track == current.left) { current.numLeft--; } } // update track and current track = current; current = current.parent; } }//end fixNodeData() // @param: x, the child of the deleted node from remove(RedBlackNode v) // Restores the Red Black properties that may have been violated during // the removal of a node in remove(RedBlackNode v) private void removeFixup(RedBlackNode<T> x) { RedBlackNode<T> w; // While we haven't fixed the tree completely... while (x != root && x.color == RedBlackNode.BLACK) { // if x is it's parent's left child if (x == x.parent.left) { // set w = x's sibling w = x.parent.right; // Case 1, w's color is red. if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; leftRotate(x.parent); w = x.parent.right; } // Case 2, both of w's children are black if (w.left.color == RedBlackNode.BLACK && w.right.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's right child is black if (w.right.color == RedBlackNode.BLACK) { w.left.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; rightRotate(w); w = x.parent.right; } // Case 4, w = black, w.right = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.right.color = RedBlackNode.BLACK; leftRotate(x.parent); x = root; } } // if x is it's parent's right child else { // set w to x's sibling w = x.parent.left; // Case 1, w's color is red if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; rightRotate(x.parent); w = x.parent.left; } // Case 2, both of w's children are black if (w.right.color == RedBlackNode.BLACK && w.left.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's left child is black if (w.left.color == RedBlackNode.BLACK) { w.right.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; leftRotate(w); w = x.parent.left; } // Case 4, w = black, and w.left = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.left.color = RedBlackNode.BLACK; rightRotate(x.parent); x = root; } } }// end while // set x to black to ensure there is no violation of // RedBlack tree Properties x.color = RedBlackNode.BLACK; }// end removeFixup(RedBlackNode x) // @param: key, the key whose node we want to search for // @return: returns a node with the key, key, if not found, returns null // Searches for a node with key k and returns the first such node, if no // such node is found returns null public RedBlackNode<T> search(T key) { // Initialize a pointer to the root to traverse the tree RedBlackNode<T> current = root; // While we haven't reached the end of the tree while (!isNil(current)) { // If we have found a node with a key equal to key if (current.key.equals(key)) // return that node and exit search(int) { return current; } // go left or right based on value of current and key else if (current.key.compareTo(key) < 0) { current = current.right; } // go left or right based on value of current and key else { current = current.left; } } // we have not found a node whose key is "key" return null; }// end search(int key) // @param: key, any Comparable object // @return: return's the number of elements greater than key public int numGreater(T key) { // Call findNumGreater(root, key) which will return the number // of nodes whose key is greater than key return findNumGreater(root, key); }// end numGreater(int key) // @param: key, any Comparable object // @return: return's teh number of elements smaller than key public int numSmaller(T key) { // Call findNumSmaller(root,key) which will return // the number of nodes whose key is greater than key return findNumSmaller(root, key); }// end numSmaller(int key) // @param: node, the root of the tree, the key who we must // compare other node key's to. // @return: the number of nodes greater than key. public int findNumGreater(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, all elements right of node are // greater than key, add this to our total and look to the left else if (key.compareTo(node.key) < 0) { return 1 + node.numRight + findNumGreater(node.left, key); } // If key is greater than node.key, then look to the right as // all elements to the left of node are smaller than key else { return findNumGreater(node.right, key); } }// end findNumGreater(RedBlackNode, int key) /** * Returns sorted list of keys greater than key. Size of list will not * exceed maxReturned * * @param key Key to search for * @param maxReturned Maximum number of results to return * @return List of keys greater than key. List may not exceed * maxReturned */ public List<T> getGreaterThan(T key, Integer maxReturned) { List<T> list = new ArrayList<T>(); getGreaterThan(root, key, list); return list.subList(0, Math.min(maxReturned, list.size())); } private void getGreaterThan(RedBlackNode<T> node, T key, List<T> list) { if (isNil(node)) { return; } else if (node.key.compareTo(key) > 0) { getGreaterThan(node.left, key, list); list.add(node.key); getGreaterThan(node.right, key, list); } else { getGreaterThan(node.right, key, list); } } // @param: node, the root of the tree, the key who we must compare other // node key's to. // @return: the number of nodes smaller than key. public int findNumSmaller(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, look to the left as all // elements on the right of node are greater than key else if (key.compareTo(node.key) <= 0) { return findNumSmaller(node.left, key); } // If key is larger than node.key, all elements to the left of // node are smaller than key, add this to our total and look // to the right. else { return 1 + node.numLeft + findNumSmaller(node.right, key); } }// end findNumSmaller(RedBlackNode nod, int key) // @param: node, the RedBlackNode we must check to see whether it's nil // @return: return's true of node is nil and false otherwise private boolean isNil(RedBlackNode node) { // return appropriate value return node == nil; }// end isNil(RedBlackNode node) // @return: return's the size of the tree // Return's the # of nodes including the root which the RedBlackTree // rooted at root has. public int size() { // Return the number of nodes to the root's left + the number of // nodes on the root's right + the root itself. return root.numLeft + root.numRight + 1; }// end size() }// end class RedBlackTree }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
59501ce1ac5bde8b8f02c47d6d9761ff
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class StrangeInequality { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String next() throws IOException { while(st == null||!st.hasMoreTokens()){ st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } static int readInt() throws IOException{ return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { int T = readInt(), n; long ans; int max = 100010; int[] fb = new int[max]; int[] ansb = new int[max]; int[] permutation = new int[max]; while (T-->0){ n = readInt(); ans = 0; for (int i = 1; i <= n; i++) { permutation[i]=readInt(); } for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { if (permutation[i]>permutation[j]){ fb[i]++; } } } for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (permutation[i]<permutation[j])fb[j]--; } ansb[0]=0; for (int j = 1; j <= i; j++) { ansb[j] = ansb[j-1]+fb[j]; } for (int j = 1; j < i; j++) { if (permutation[i]>permutation[j]){ ans+=ansb[i-1]-ansb[j]; } } } System.out.println(ans); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b5481722888601de6fbb4f7e8891e40d
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); // int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { // out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n; // out.print("Case #"+(a++)+": ") n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } long ans = 0; long a; int c = 1; while (c <= n) { c = c << 1; } // System.out.println(c); int[] tree1 = new int[2 * c - 1]; c--; // int c = 8191; // for (int i = 0; i <= n; i++) { // tree[i] = 0; // tree1[i] = 0; // } // Arrays.fill(tree,0); // Arrays.fill(tree1,0); long[][] array = new long[n][n]; set(arr[0] - 1, 1, 0, 0, c, tree1); for (int i = 2; i < n - 1; i++) { a = sum(0, arr[i] - 2, 0, 0, c, tree1); for (int j = i - 1; j > 0; j--) { if (j != i - 1) { if (arr[j] < arr[i]) { a--; } } array[i][j] = a; // b = sum(0, arr[j] - 2, 0, 0, c, tree); // ans += a * b; } // set(arr[i + 1] - 1, 0, 0, 0, c, tree); set(arr[i - 1] - 1, 1, 0, 0, c, tree1); } Arrays.fill(tree1, 0); for (int i = 3; i < n; i++) { set(arr[i] - 1, 1, 0, 0, c, tree1); } for (int i = 1; i < n - 2; i++) { a = sum(0, arr[i] - 2, 0, 0, c, tree1); for (int j = i + 1; j < n - 1; j++) { if (j != i + 1) { if (arr[j] < arr[i]) { a--; } } array[j][i] *= a; // b = sum(0, arr[j] - 2, 0, 0, c, tree); // ans += a * b; } // set(arr[i + 1] - 1, 0, 0, 0, c, tree); set(arr[i + 2] - 1, 0, 0, 0, c, tree1); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ans+=array[i][j]; } } out.println(ans); } public int sum(int l, int r, int root, int lx, int rx, int[] tree) { if (r < lx || rx < l) { return 0; } if (l <= lx && rx <= r) { return tree[root]; } int mid = (lx + rx) / 2; return sum(l, r, 2 * root + 1, lx, mid, tree) + sum(l, r, 2 * root + 2, mid + 1, rx, tree); } public void set(int index, int value, int root, int lx, int rx, int[] tree) { if (lx == rx) { tree[root] = value; return; } int mid = (lx + rx) / 2; if (index <= mid) { set(index, value, 2 * root + 1, lx, mid, tree); } else { set(index, value, 2 * root + 2, mid + 1, rx, tree); } tree[root] = tree[2 * root + 1] + tree[2 * root + 2]; } } static long mod = 1_000_000_007; static long mul(long a, long b) { return a * b % mod; } static long exp(long base, long pow) { if (pow == 0) return 1; long half = exp(base, pow / 2); if (pow % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static int gcd(int a, int b ) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a, b; long c; public answer(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return Integer.compare(this.a, o.a); } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public answer1(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer1 o) { if(this.b == o.b){ return Integer.compare(this.a, o.a); } return Integer.compare(this.b, o.b); } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (Long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi= random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
11fcecc33fa36dfc7ec111be6ac8f1c1
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; // @author : Dinosparton public class test { static class Pair{ long x; long y; Pair(long x,long y){ this.x = x; this.y = y; } } static class Triplet{ long x; long y; double ratio; Triplet(long x,long y,double ratio){ this.x = x; this.y = y; this.ratio = ratio; } } static class Sort implements Comparator<Pair> { @Override public int compare(Pair a, Pair b) { if(a.x!=b.x) { return (int)(a.x - b.x); } else { return (int)(a.y-b.y); } } } static class Compare { void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x!=p2.x) { return (int)(p1.x - p2.x); } else { return (int)(p1.y - p2.y); } } }); // for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class FenwickTree { public long[] tree; public int size; public FenwickTree(int size) { this.size = size; tree = new long[size + 5]; } public void add(int i, long v) { while (i <= size) { tree[i] += v; i += i & -i; } } public long find(int i) { long res = 0; while (i >= 1) { res += tree[i]; i -= i & -i; } return res; } public long find(int l, int r) { return find(r) - find(l - 1); } } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(); StringBuilder res = new StringBuilder(); int tc = sc.nextInt(); while(tc-->0) { int n = sc.nextInt(); int p[] = new int[n]; for(int i=0;i<n;i++) { p[i] = sc.nextInt(); } FenwickTree ft = new FenwickTree(n + 5); long cnt = 0; for(int c = n-1;c>=0;c--) { long ans = 0; for(int a = c-1;a>=0;a--) { if(p[a] < p[c]) { cnt += ans; } ans += ft.find(1,p[a]); } ft.add(p[c], 1); } res.append(cnt+"\n"); } System.out.println(res); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
6f7c4b5a9221c1357a871ad76cefd0c4
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class G { static FastScanner fs = new FastScanner(); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(""); static Scanner scn = new Scanner(System.in); public static void main(String[] args) { int t = fs.nextInt(); //int t = 1; for (int tt = 0; tt < t; tt++) { int n = fs.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = fs.nextInt()-1; int[] cnt = new int[n]; long ans = 0; for (int i = 0; i < n; i++) { int x = 0; for (int j = n-1; j > i; j--) { ans += cnt[j] * x; x += (a[j] < a[i]) ? 1 : 0; cnt[j] += (a[i] < a[j]) ? 1 : 0; } } sb.append(ans + "\n"); } pw.print(sb.toString()); pw.close(); } static void sort(int[] a) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) al.add(i); Collections.sort(al); for (int i = 0; i < a.length; i++) a[i] = al.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() {while (!st.hasMoreTokens())try {st = new StringTokenizer(br.readLine());} catch (IOException e) {}return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) {a[i] = nextInt();} return a;} } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
dae8c78eee4bbbbf7c84c5e8f570ec90
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int [] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } long [][] memo = new long[n][n]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (j > 0) memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } for (int j = i+1; j < n; j++) { memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } } long ans = 0; for (int i = 1; i < n-2; i++) { // left for (int j = i+1; j < n-1; j++) { // right ans += (memo[j][i-1] * (memo[i][n-1] - memo[i][j])); } } System.out.println(ans); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } int[] sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i : arr) list.add(i); Collections.sort(list); int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = list.get(i); return res; } void debug(int a) { System.out.println("This is var " + a); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5e7129a6728df6f97013a34a53051786
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class C{ public static void main(String[] args) { FastReader sc = new FastReader(); StringBuilder sb = new StringBuilder(); int t = sc.nextInt(); out:while(t-- >0) { int n = sc.nextInt(); int[] p = sc.readArray(n); long[] dp = new long[n]; long ans = 0l; for(int c=n-1;c>=0;c--) { long cnt = 0; for(int a = c-1;a>=0;a--) { if(p[a]<p[c]) { ans += cnt; } cnt+=dp[a]; if(p[a]>p[c]) { dp[a]++; } } } sb.append(ans).append("\n"); } System.out.println(sb); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9d09487da84d1cc0a6d359f9a6f26476
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { void go() { int n = Reader.nextInt(); int[] A = new int[n]; int[] cnt = new int[n]; long ans = 0; for(int i = 0; i < n; i++) { A[i] = Reader.nextInt(); } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { cnt[i] += (A[j] < A[i] ? 1 : 0); } } for(int i = 1; i < n; i++) { int c = A[i]; for(int j = 0; j < i; j++) { if(A[j] > c) { cnt[j]--; } } long[] psum = new long[n + 1]; for(int j = 1; j <= i; j++) { psum[j] = psum[j - 1] + cnt[j - 1]; } for(int j = 0; j < i - 1; j++) { int a = A[j]; if(a < c) { ans += psum[i] - psum[j + 1]; } } } Writer.println(ans); } void solve() { for(int T = Reader.nextInt(); T > 0; T--) go(); } void run() throws Exception { Reader.init(System.in); Writer.init(System.out); solve(); Writer.close(); } public static void main(String[] args) throws Exception { new C().run(); } public static class Reader { public static StringTokenizer st; public static BufferedReader br; public static void init(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public static String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } return st.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } } public static class Writer { public static PrintWriter pw; public static void init(OutputStream os) { pw = new PrintWriter(new BufferedOutputStream(os)); } public static void print(String s) { pw.print(s); } public static void print(char c) { pw.print(c); } public static void print(int x) { pw.print(x); } public static void print(long x) { pw.print(x); } public static void println(String s) { pw.println(s); } public static void println(char c) { pw.println(c); } public static void println(int x) { pw.println(x); } public static void flush() { pw.flush(); } public static void println(long x) { pw.println(x); } public static void close() { pw.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9da4c856900718f0a85c5bd5481d2d07
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class C { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String sc[] = br.readLine().split(" "); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(sc[i]); } int mt[][] = new int[n + 1][n]; for (int i = 1; i < n - 2; i++) { int prev = 0; for (int j = n - 1; j > i + 1; j--) { mt[a[i]][j] = prev; if (a[i] > a[j]) { prev++; mt[a[i]][j] = prev; } } } int s[][] = new int[n][n]; for (int i = 2; i < n - 1; i++) { for (int j = i - 1; j >= 1; j--) { s[i][j] = s[i][j + 1] + mt[a[j]][i + 1]; // bw.write(s[i][j] + " "); } // bw.newLine(); } long ans = 0; for (int i = 0; i < n - 3; i++) { for (int j = i + 2; j < n - 1; j++) { if (a[i] < a[j]) { ans = ans + (long) s[j][i + 1]; } } } bw.write(ans + "\n"); } bw.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
144712e3fecd63f8e65484f974619bbe
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import javax.swing.*; import java.sql.SQLSyntaxErrorException; import java.util.*; import java.io.*; import java.math.*; import java.util.stream.StreamSupport; public class Solution { // static int mod = 998244353; static int mod = 1000000007; public static void main(String str[]) throws IOException{ Reader sc = new Reader(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); // Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); ArrayList<Integer> al = new ArrayList<>(); long ans = 0; int[] index = new int[n+1]; for(int i=0;i<n;i++){ int ind = Collections.binarySearch(al,arr[i]); ind++; ind*=-1; al.add(ind,arr[i]); int temp = ind; index[arr[i]] = ind; for(int j=i-1;j>=0;j--){ if(arr[j]<arr[i]){ temp--; } else{ index[arr[j]]++; } int ind2 = index[arr[j]]; long res = (arr[j]-ind2-1)*temp; if(res<0) res = 0; ans+=res; } } output.write(ans+"\n"); } output.flush(); } static void fun(int[] arr, int k){ int n = arr.length; int max = 0; int ind = -1; for(int i=0;i<n;i++){ if(arr[i]>k){ ind = i; break; } max = Math.max(max, arr[i]); } k-=max; int m2 = 0; int next = 0; if(ind!=-1){ m2 = arr[ind]; next = m2-k; } for(int i=0;i<n;i++){ if(arr[i]<=max) arr[i] = 0; if(arr[i]<=m2 && arr[i]>next) arr[i] = next; } } static void dfs(Node[] arr, ArrayList<ArrayList<Integer>> al, ArrayList<Integer> curr, int root){ curr.add(root+1); if(!arr[root].al.isEmpty()){ dfs(arr, al, curr, arr[root].al.get(0)); } else al.add(curr); if(arr[root].al.size()>1) { for(int i=1;i<arr[root].al.size();i++) { ArrayList<Integer> next = new ArrayList<>(); dfs(arr, al, next, arr[root].al.get(i)); } } } static class Node{ int ind; ArrayList<Integer> al = new ArrayList<>(); Node(int ii){ ind = ii; } } static int bfsAtD(Graph[] g, int start, int end,int D){ int[] visited = new int[g.length]; int[] twoV = new int[g.length]; Arrays.fill(visited,-1); LinkedList<Pair> queue = new LinkedList<Pair>(); visited[start] = 0; Pair p = new Pair(start, 0); queue.add(p); int count = 0; while (queue.size() != 0) { Pair s = queue.poll(); int dis = s.two+1; for(int i: g[s.one].pq) { int n = i; if(n==end && (dis<=D)) count++; if(twoV[n]==0){ visited[n] = dis; twoV[n]++; Pair temp = new Pair(n, dis); queue.add(temp); } else if(twoV[n]==1 && dis-1==visited[n]){ twoV[n]++; Pair temp = new Pair(n, dis); queue.add(temp); } } } return count; } static int bfs(Graph[] g, int start, int end,boolean[] visited){ LinkedList<Pair> queue = new LinkedList<Pair>(); visited[start]=true; Pair p = new Pair(start, 0); queue.add(p); while (queue.size() != 0) { Pair s = queue.poll(); int dis = s.two+1; for(int i: g[s.one].pq) { int n = i; if(n==end) return dis; if (!visited[n]) { visited[n] = true; Pair temp = new Pair(n,dis); queue.add(temp); } } } return -1; } static class Pair { int one; int two; // int e=0; Pair(int v, int ss) { one = v; two = ss; } } static int GCD(int a, int b) { return (a % b == 0) ? Math.abs(b) : GCD(b,a%b); } static int knapSack(int W, int wt[], int val[], int n) { // making and initializing dp array int []dp = new int[W + 1]; for (int i = 1; i < n + 1; i++) { for (int w = W; w >= 0; w--) { if (wt[i - 1] <= w) // finding the maximum value dp[w] = Math.max(dp[w], dp[w - wt[i - 1]] + val[i - 1]); } } return dp[W]; // returning the maximum value of knapsack } static int dp(ArrayList<Integer> arr, ArrayList<Integer> num, HashMap<Double, Integer> memo, double curr, int ans){ if(memo.containsKey((Math.pow(ans,4)*Math.pow(curr,3)))) return memo.get(curr); int max = 0; int fin = 0; for(int i=0;i<arr.size();i++){ int x = arr.get(i); arr.remove(i); int y = num.get(i); num.remove(i); int pp = x; if(ans!=-1) pp = (int)gcd(ans, x); if(pp==1){ int temp = pp+arr.size(); if(max<=temp){ max = temp; fin = pp; } continue; } int temp = pp + dp(arr, num, memo, curr+(Math.pow(x,7)/Math.pow(x,4)), pp); if(max<=temp){ max = temp; fin = pp; } num.add(i,y); arr.add(i,x); } memo.put(curr, max); return max+fin; } static int max(ArrayList<Integer> al){ int i=0; int max =Integer.MIN_VALUE; for(int j=0;j<al.size();j++){ int k = al.get(j); if(k>max){ i = j; max = k; } } return i; } //Collections.sort(al, new Comparator<Object>() { // @Override // public int compare(Object o1, Object o2) { // return 0; // } //}); // static class Node{ // int ind; // int tot = 1; // ArrayList<Node> parent = new ArrayList<>(); // ArrayList<Node> child = new ArrayList<>(); // Node(int i){ // ind =i; // } // } // // } static int maxHeight(List<Integer> wallPositions, List<Integer> wallHeights){ int ans = 0; int n = wallHeights.size(); for(int i=1;i<n;i++){ int ind1 = wallPositions.get(i-1); int ind2 = wallPositions.get(i); if(ind2-ind1==1) continue; int x = wallHeights.get(i-1); int y = wallHeights.get(i); int index = (y-x+ind1+ind2)/2; if(index<=ind1){ index = ind1+1; } else if(index>=ind2){ index = ind2-1; } ans = Math.max(ans, Math.min(x+(index-ind1),y+(ind2-index))); } return ans; } // 3 // 2 1 1 // 2 3 11 // 3 4 1 // 4 // 2 public static ArrayList<Integer> primeFactors(int n) { // Print the number of 2s that divide n ArrayList<Integer> al = new ArrayList<>(); while (n%2==0) { al.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { al.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) al.add(n); return al; } // static class tempSort implements Comparator<Node> { // // Used for sorting in ascending order of // // roll number // public int compare(Node a, Node b) { // return a.size - b.size; // } // } static long modDivision(long p, long q, long mod){ p = p%mod; long inv = modInverse(q, mod); return (inv*p) %mod; } static long divide(long p, long q, long mod) { long expo = mod - 2; while (expo != 0) { if ((expo & 1) == 1) { // long temp = p; // System.out.println("zero--> "+temp+" "+q); p = (p * q) % mod; // if(p<0){ // System.out.println("one--> "+temp+" "+q); // } } q = (q * q) % mod; // if(q<0){ // System.out.println("two--> "+p+" "+q); // } expo >>= 1; } return p; } static class Graph{ int ind; ArrayList<Integer> pq = new ArrayList<>(); Set<Integer> set; boolean b = false; public Graph(int a){ ind = a; } } // // static class Pair{ // int a=0; // int b=0; // int in = 0; // int ac = 0; // int ex = 0; // } long fun2(ArrayList<Integer> arr, int x){ ArrayList<ArrayList> al = new ArrayList<>(); ArrayList<Integer> curr = new ArrayList<>(); fun(arr, x, al, curr, 0); if(al.size()==0) return 0; int max = 0; for(ArrayList<Integer> i: al){ if(i.size()>max) max = i.size(); } for(int i=0;i<al.size();i++){ if(al.get(i).size()!=max){ al.remove(i); i--; } } for(ArrayList<Integer> i: al){ Collections.sort(al, Collections.reverseOrder()); } long ans = 0; for(ArrayList<Integer> i: al){ long temp = 0; for(int j: i){ temp*=10; temp+=j; } if(ans<temp) ans = temp; } return ans; } void fun(ArrayList<Integer> arr, int x, ArrayList<ArrayList> al, ArrayList<Integer> curr, int i){ if(x<0) return ; if(x==0) { al.add(curr); return; } for(int j=i;j<arr.size();j++){ ArrayList<Integer> temp = new ArrayList<>(curr); fun(arr, x-arr.get(j), al, temp, j); } } // Returns n^(-1) mod p static long modInverse(long n, long p) { return (long)power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, int p, long[] fac) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long x = modInverse(fac[r], p); long y = modInverse(fac[n - r], p); return (fac[n] * x % p * y % p) % p; } static long[] sum(String[] str){ int n = str[0].length(); long ans[] = new long[n]; for(String s: str){ for(int i=0;i<n;i++) ans[i]+=s.charAt(i); } return ans; } // static class tSort implements Comparator<Pair>{ // // public int compare(Pair s1, Pair s2) { // if (s1.b < s2.b) // return -1; // else if (s1.b > s2.b) // return 1; // return 0; // } // } // static boolean checkCycle(Tree[] arr, boolean[] visited, int curr, int Node){ // if(curr==Node && visited[curr]) return true; // if(visited[curr]) return false; // visited[curr] = true; // for(int i: arr[curr].al){ // if(checkCycle(arr, visited, i, Node)) return true; // } // return false; // } // static boolean allCombinations(int n){ //Global round 15 // int three2n = 1; // for (int i = 1; i <= n; i++) // three2n *= 3; // // for (int k = 1; k < three2n; k++) { // int k_cp = k; // int sum = 0; // for (int i = 1; i <= n; i++) { // int s = k_cp % 3; // k_cp /= 3; // if (s == 2) s = -1; // sum += s * a[i]; // } // if (sum == 0) { // return true; // } // } // return false; // } static ArrayList<String> fun( int curr, int n, char c){ int len = n-curr; if(len==0) return null; ArrayList<String> al = new ArrayList<>(); if(len==1){ al.add(c+""); return al; } String ss = ""; for(int i=0;i<len/2;i++){ ss+=c; } ArrayList<String> one = fun(len/2+curr, n, (char)(c+1)); for(String str: one){ al.add(str+ss); al.add(ss+str); } return al; } static ArrayList convert(int x, int k){ ArrayList<Integer> al = new ArrayList<>(); if(x>0) { while (x > 0) { al.add(x % k); x /= k; } } else al.add(0); return al; } static int max(int x, int y, int z){ int ans = Math.max(x,y); ans = Math.max(ans, z); return ans; } static int min(int x, int y, int z){ int ans = Math.min(x,y); ans = Math.min(ans, z); return ans; } // static long treeTraversal(Tree arr[], int parent, int x){ // long tot = 0; // for(int i: arr[x].al){ // if(i!=parent){ // tot+=treeTraversal(arr, x, i); // } // } // arr[x].child = tot; // if(arr[x].child==0) arr[x].child = 1; // return tot+1; // } public static int primeFactors(int n, int k) { int ans = 0; while (n%2==0) { ans++; if(ans>=k) return k; n /= 2; } for (int i = 3; i <= Math.sqrt(n); i+= 2) { while (n%i == 0) { ans++; n /= i; if(ans>=k) return k; } } if (n > 2) ans++; return ans; } static int binaryLow(ArrayList<Integer> arr, int x, int s, int e){ if(s>=e){ if(arr.get(s)>=x) return s; else return s+1; } int m = (s+e)/2; if(arr.get(m)==x) return m; if(arr.get(m)>x) return binaryLow(arr,x,s,m); if(arr.get(m)<x) return binaryLow(arr,x,m+1,e); return 0; } static int binaryLow(int[] arr, int x, int s, int e){ if(s>=e){ if(arr[s]>=x) return s; else return s+1; } int m = (s+e)/2; if(arr[m]==x) return m; if(arr[m]>x) return binaryLow(arr,x,s,m); if(arr[m]<x) return binaryLow(arr,x,m+1,e); return 0; } static int binaryHigh(int[] arr, int x, int s, int e){ if(s>=e){ if(arr[s]<=x) return s; else return s-1; } int m = (s+e)/2; if(arr[m]==x) return m; if(arr[m]>x) return binaryHigh(arr,x,s,m-1); if(arr[m]<x) return binaryHigh(arr,x,m+1,e); return 0; } // static void arri(int arr[], int n, Reader sc) throws IOException{ // for(int i=0;i<n;i++){ // arr[i] = sc.nextInt(); // } // } // static void arrl(long arr[], int n, Reader sc) throws IOException{ // for(int i=0;i<n;i++){ // arr[i] = sc.nextLong(); // } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res%p; } // static class SortbyI implements Comparator<Pair> { // // Used for sorting in ascending order of // // roll number // public int compare(Pair a, Pair b) // { // if(a.a>=b.a) return 1; // else return -1; // } // } // static class SortbyD implements Comparator<Pair> { // // Used for sorting in ascending order of // // roll number // public int compare(Pair a, Pair b) // { // if(a.a<b.a) return 1; // else if(a.a==b.b && a.b>b.b) return 1; // else return -1; // } // } // static int binarySearch(ArrayList<Pair> a, int x, int s, int e){ // if(s>=e){ // if(x<=a.get(s).b) return s; // else return s+1; // } // int mid = (e+s)/2; // if(a.get(mid).b<x){ // return binarySearch(a, x, mid+1, e); // } // else return binarySearch(a,x,s, mid); // } // static class Edge{ // int a; // int b; // int c; // int sec; // Edge(int a, int b, int c, int sec){ // this.a = a; // this.b = b; // this.c = c; // this.sec = sec; // } // // } static class Tree{ int a; ArrayList<Tree> al = new ArrayList<>(); Tree(int a){ this.a = a; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine(int n) throws IOException { byte[] buf = new byte[n+1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static ArrayList<Integer> sieveOfEratosthenes(int n) { ArrayList<Integer> al = new ArrayList<>(); // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) al.add(i); } return al; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
645f665cfdc2c795d07b6137aff6da1a
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static int[] BIT; private static void update(int index, int add) { while(index < BIT.length) { BIT[index] += add; index += index&-index; } } private static int query(int index) { int sum = 0; while(index > 0) { sum += BIT[index]; index -= index&-index; } return sum; } public static void main(String[] args) throws IOException { //BufferedReader f = new BufferedReader(new FileReader("paintbarn.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); int[] p = new int[n]; for(int i = 0; i < n; i++) { p[i] = Integer.parseInt(st.nextToken()); } BIT = new int[n+1]; long ans = 0; for(int i = 0; i < n; i++) { for(int j = i+2; j < n; j++) { if(p[i] > p[j]) { ans += query(j-1)-query(i); } } for(int j = i+2; j < n; j++) { if(p[i] < p[j]) { update(j, 1); } } } out.println(ans); } f.close(); out.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
3787c0122bf0f05e1cce5bcbef32d36b
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } int binary(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } static int[] segment; static void constructSt(int n, int[] arr){ segment = new int[n*4+1]; formSt(arr, 1,0,n-1); } public static void formSt(int[] arr, int node, int s, int e){ if(s==e){ segment[node]= arr[s]; return; } formSt(arr, node*2,s,s+(e-s)/2); formSt(arr, node*2+1,s+(e-s)/2+1,e); segment[node]=Math.max(segment[node*2],segment[node*2+1]); } public static int findMax( int node, int s, int e,int l , int r){ if(l>e||s>r) return -1; if(s==e) return segment[node]; if(l<=s&&r>=e) return segment[node]; int mid = s+(e-s)/2; return Math.max(findMax(node*2,s,mid,l,r),findMax(node*2+1,mid+1,e,l,r)); } public static void main (String[] args) throws java.lang.Exception { OutputStream outputStream =System.out; PrintWriter out =new PrintWriter(outputStream); FastReader sc =new FastReader(); int t =sc.nextInt(); while(t-->0){ int n =sc.nextInt(); int[][] p = new int[n][n], s= new int[n][n]; int[] a = new int[n]; long sum=0; for(int i =0;i<n;i++) a[i]=sc.nextInt(); for(int i =0;i<n;i++) for(int j =n-1;j>i;j--){ if(a[i]>a[j]) p[i][j]=j<n-1?p[i][j+1]+1:1; else if(j<n-1) p[i][j]=p[i][j+1]; } for(int i =1;i<n;i++) for(int j =0;j<i;j++){ if(a[i]>a[j]) s[i][j]=j>0?s[i][j-1]+1:1; else if(j>0) s[i][j]=s[i][j-1]; } for(int i =1;i<n-2;i++) for(int j =i+1;j<n-1;j++) sum+= s[j][i-1]*p[i][j+1]; out.print(sum+"\n"); } out.close(); // your code goes here" } } class pair { long r; long d; public pair(long r , long d) { this.r= r; this.d= d; } } class solution{ }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
c00ff212814485bb55f88924e40885aa
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.util.function.BiFunction; import java.io.*; // you can compare with output.txt and expected out public class Round789C { MyPrintWriter out; MyScanner in; final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void preferFileIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round789C sol = new Round789C(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; preferFileIO(isFileIO); int t = in.nextInt(); for (int i = 1; i <= t; ++i) { int n = in.nextInt(); int[] p = in.nextIntArray(n, -1); if(isDebug){ out.printf("Test %d\n", i); } long ans = solve(p); out.println(ans); if(isDebug) out.flush(); } in.close(); out.close(); } private long solve(int[] p) { int n = p.length; // # increasing pair * # decreasing pair doesn't work // all increasing pair front and all decreasing pair back // for each pair (p_b > p_d), insert to DS // s.t. this adds 1 to all intervals [a, c] s.t. a < b < c < d // can this impose an order to intervals: [a, c] < [b, d] iff a < b < c < d? // no this is not transitive // # of elements > value, of index >= index // larger[value][index] // # of elements < value, of index >= index // smalller[value][index] // int[][] larger = new int[n][n]; int[][] smaller = new int[n][n]; for(int val=0; val<n; val++) { // if(p[n-1] > val) // larger[val][n-1] = 1; // else if(p[n-1] < val) // smaller[val][n-1] = 1; if(p[n-1] < val) smaller[val][n-1] = 1; } for(int i=n-2; i>=0; i--) { for(int val=0; val<n; val++) { // larger[val][i] = larger[val][i+1]; // smaller[val][i] = smaller[val][i+1]; // if(p[i] > val) { // larger[val][i]++; // } // else if(p[i] < val) { // smaller[val][i]++; // } smaller[val][i] = p[i]<val? smaller[val][i+1]+1: smaller[val][i+1]; } } // int[][] largerValidator = check(p, (x, y) -> x>y); // int[][] smallerValidator = check(p, (x, y) -> x<y); // System.out.println(Arrays.deepEquals(larger, largerValidator)); // System.out.println(Arrays.deepEquals(smaller, smallerValidator)); // for each pair (b, c) // # elem < p[c] left to b * # elem < p[b] right to c long val = 0; for(int b=1; b<n-2; b++) { for(int c=b+1; c<n-1; c++) { long temp = smaller[p[c]][0] - smaller[p[c]][b]; temp *= smaller[p[b]][c+1]; val += temp; } } return val; } private int[][] check(int[] p, BiFunction<Integer, Integer, Boolean> f) { int n = p.length; int[][] ans = new int[n][n]; // # of elements > value, of index >= index // larger[value][index] for(int val=0; val<n; val++) { for(int idx=0; idx<n; idx++) { for(int i=idx; i<n; i++) { if(f.apply(p[i], val)) ans[val][idx]++; } } } return ans; } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextGraphEdges(){ return nextGraphEdges(0); } int[][] nextGraphEdges(int offset) { int m = nextInt(); int[][] e = new int[m][2]; for(int i=0; i<m; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void print(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(long[] arr){ print(arr); println(); } public void print(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(int[] arr){ print(arr); println(); } public <T> void print(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void println(ArrayList<T> arr){ print(arr); println(); } public void println(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void println(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; int[] idx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][idx[u]++] = v; neighbors[v][idx[v]++] = u; } return neighbors; } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
d041ac4c1effcbcf3cd2b33a638aa3da
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.util.function.BiFunction; import java.io.*; // you can compare with output.txt and expected out public class Round789C { MyPrintWriter out; MyScanner in; final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void preferFileIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round789C sol = new Round789C(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; preferFileIO(isFileIO); int t = in.nextInt(); for (int i = 1; i <= t; ++i) { int n = in.nextInt(); int[] p = in.nextIntArray(n, -1); if(isDebug){ out.printf("Test %d\n", i); } long ans = solve(p); out.println(ans); if(isDebug) out.flush(); } in.close(); out.close(); } private long solve(int[] p) { int n = p.length; // # increasing pair * # decreasing pair doesn't work // all increasing pair front and all decreasing pair back // for each pair (p_b > p_d), insert to DS // s.t. this adds 1 to all intervals [a, c] s.t. a < b < c < d // can this impose an order to intervals: [a, c] < [b, d] iff a < b < c < d? // no this is not transitive // # of elements > value, of index >= index // larger[value][index] // # of elements < value, of index >= index // smalller[value][index] int[][] larger = new int[n][n]; int[][] smaller = new int[n][n]; for(int val=0; val<n; val++) { if(p[n-1] > val) larger[val][n-1] = 1; else if(p[n-1] < val) smaller[val][n-1] = 1; } for(int i=n-2; i>=0; i--) { for(int val=0; val<n; val++) { larger[val][i] = larger[val][i+1]; smaller[val][i] = smaller[val][i+1]; if(p[i] > val) { larger[val][i]++; } else if(p[i] < val) { smaller[val][i]++; } } } // int[][] largerValidator = check(p, (x, y) -> x>y); // int[][] smallerValidator = check(p, (x, y) -> x<y); // System.out.println(Arrays.deepEquals(larger, largerValidator)); // System.out.println(Arrays.deepEquals(smaller, smallerValidator)); // for each pair (b, c) // # elem < p[c] left to b * # elem < p[b] right to c long val = 0; for(int b=1; b<n-2; b++) { for(int c=b+1; c<n-1; c++) { long temp = smaller[p[c]][0] - smaller[p[c]][b]; temp *= smaller[p[b]][c+1]; val += temp; } } return val; } private int[][] check(int[] p, BiFunction<Integer, Integer, Boolean> f) { int n = p.length; int[][] ans = new int[n][n]; // # of elements > value, of index >= index // larger[value][index] for(int val=0; val<n; val++) { for(int idx=0; idx<n; idx++) { for(int i=idx; i<n; i++) { if(f.apply(p[i], val)) ans[val][idx]++; } } } return ans; } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextGraphEdges(){ return nextGraphEdges(0); } int[][] nextGraphEdges(int offset) { int m = nextInt(); int[][] e = new int[m][2]; for(int i=0; i<m; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void print(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(long[] arr){ print(arr); println(); } public void print(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(int[] arr){ print(arr); println(); } public <T> void print(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void println(ArrayList<T> arr){ print(arr); println(); } public void println(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void println(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; int[] idx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][idx[u]++] = v; neighbors[v][idx[v]++] = u; } return neighbors; } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
40658ee867a9c2623b0cc29d5e8397a7
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class k { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } //---------------------MATHS-------------------- public static ArrayList<Long> divisor(long n) { ArrayList<Long> arr=new ArrayList<Long>(); long x=(long) Math.sqrt(n); for (long i=1; i<=x; i++) { if (n%i == 0) { if (n/i == i) arr.add(i); else arr.add( i); arr.add( (n/i)); } } return arr; } public static ArrayList<Long> Factors(long n) { ArrayList<Long> arr=new ArrayList<Long>(); while (n%2l==0) { n /=2; arr.add(2l); } long p=(long) Math.sqrt(n); for (long i = 3; i <=p; i+= 2) { if(n==1)break; while (n%i == 0) { arr.add(i); n /= i; } } if (n > 2) { arr.add(n); } return arr; } static long hcf(long a,long b) { while (b > 0) { long temp = b; b = a % b; a = temp; } return a; } public static long gcd(long x, long p) { if (x == 0) return p; return gcd(p%x, x); } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static int biggestFactor(int num) { int result = 1; for(int i=2; i*i <=num; i++){ if(num%i==0){ result = num/i; break; } } return result; } static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; static ArrayList<Integer> pr=new ArrayList<Integer>(); public static void sieveOfEratosthenes() { // FALSE == prime and 1 // TRUE == COMPOSITE // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N // size - 1e7(at max) for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { pr.add(p); for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } static long isPrime(long x) { if (x >= 0) { long sr = (long)Math.sqrt(x); long k=sr*sr; if(k == x)return sr; } return -1; } public static long pwmd(long a, long n,long mod) { if (n == 0) return 1; long pt = pwmd(a, n / 2,mod); pt *= pt; pt %= mod; if ((n & 1) > 0) { pt *= a; pt %= mod; } return pt; } static long nCr(long n, long r) { return (long)fact(n) / (long)(fact(r) * fact(n - r)); } // Returns factorial of n static long fact(long n) { long res = 1; for (int i = 2; i <= n; i++) res = res * (long)(i); return res; } //-------------------------BINARY SEARCHES-------------------------------------- //if present - return the first occurrence of the no //not present- return the index of next greater value //if greater than all the values return N(taking high=N-1) //if smaller than all the values return 0(taking low =0) static int lower_bound(long arr[], int low,int high, long X) { if (low > high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } return lower_bound(arr, mid + 1, high, X); } //if present - return the index of next greater value //not present- return the index of next greater value //if greater than all the values return N(taking high=N-1) //if smaller than all the values return 0(taking low =0)\ static int upper_bound(long arr[], int low, int high, long X) { if (low > high) return low; int mid = low + (high - low) / 2; if (arr[mid] <= X) { return upper_bound(arr, mid + 1,high, X); } return upper_bound(arr, low,mid - 1, X); } public static class Pair {// comparator with class long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } } //---------------UTIL--------------------- public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) { List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } public static void printArr(int[] arr) { for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } System.out.println(); } public static int[] decSort(int[] arr) { int[] arr1 = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray(); return arr1; } public static void sortbyColumn(int arr[][], int col) // send 2d array and col no { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else if (entry1[col] < entry2[col]) return -1; else return 0; } }); } public static void print2D(long[][] dp) { for (int i = 0; i < dp.length; i++) { { for (int j = 0; j < dp[i].length; j++) System.out.print(dp[i][j] + " "); } System.out.println(); } } public static int knapsack(int[] weights,int[] price, int totW) { int[] dp1=new int[totW+1]; int[] dp2=new int[totW+1]; int N=totW; int ans=0; for(int i=0;i<price.length;i++) { for(int j=0;j<=N;j++) { if(weights[i]>j) { if(i%2==0) { dp1[j]=dp2[j]; } else { dp2[j]=dp1[j]; } } else { if(i%2==0) { dp1[j]=Math.max(dp2[j],dp2[j-weights[i]]+price[i]); } else { dp2[j]=Math.max(dp1[j], dp1[j-weights[i]]+price[i]); } } } if(i%2==0)ans=dp1[N]; else ans=dp2[N]; } return ans; } public static class p { long no; long h; public p(long no, long h) { this.no=no; this.h= h; } } static class com implements Comparator<p>{ public int compare(p s1, p s2) { if (s1.h > s2.h) return -1; else if (s1.h < s2.h) return 1; else if(s1.h==s2.h) { if(s1.no>s2.no)return -1; else return 1; } return 0; } } static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) { SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>( new Comparator<Map.Entry<K,V>>() { @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) { int res = e1.getValue().compareTo(e2.getValue()); return res != 0 ? res : 1; // Special fix to preserve items with equal values } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries; } public static void floodFill1(int[][] image, int sr, int sc) { image[sr][sc]=2; if((sr-1>=0) && image[sr-1][sc]==1) { floodFill1(image,sr-1,sc); } if((sr+1<image.length) && image[sr+1][sc]==1) { floodFill1(image,sr+1,sc); } if((sc-1>=0) && image[sr][sc-1]==1 ) { floodFill1(image,sr,sc-1); } if((sc+1<image[0].length) && image[sr][sc+1]==1) { floodFill1(image,sr,sc+1); } } // ---------------SEGMENT TREE---------- public static void buildTree(long[] arr,long[][] tree,int st, int en,int ind) { // int x = (int) (Math.ceil(Math.log(arr.length) / Math.log(2))); // int size = 2 * (int) Math.pow(2, x) - 1; // int[] tree=new int[size]; if(st==en) {tree[ind][0]=arr[st];tree[ind][1]=1;return;} int mid=(st+en)/2; buildTree(arr,tree,st,mid,2*ind); buildTree(arr,tree,mid+1,en,(2*ind)+1); if(tree[2*ind][0]<tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind][0]; tree[ind][1]=tree[2*ind][1]; } if(tree[2*ind][0]>tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind+1][0]; tree[ind][1]=tree[2*ind+1][1]; } if(tree[2*ind][0]==tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind][0]; tree[ind][1]=tree[2*ind][1]+tree[2*ind+1][1]; } return; } public static int k=0; public static long query(long[][] tree,int st, int en, int qs, int qe, int ind) { if(st>=qs && en<=qe) { return tree[ind][0]; } if(st>qe || en<qs)return Integer.MAX_VALUE; int mid=(st+en)/2; long l=query(tree,st,mid,qs,qe,2*ind); long r=query(tree,mid+1,en,qs,qe,2*ind+1); return Math.min(l, r); } public static p query1(long[][] tree,int st, int en, int qs, int qe, int ind) { if(st>qe || en<qs) { p k=new p(1000000007,-1); return k; } if(st>=qs && en<=qe) { return new p(tree[ind][0],tree[ind][1]); } int mid=(st+en)/2; p l=query1(tree,st,mid,qs,qe,2*ind); p r=query1(tree,mid+1,en,qs,qe,2*ind+1); p fin; if(l.no<r.no) { return l; } if(l.no>r.no) { return r; } return new p(l.no,l.h+r.h); } public static void update(long[][] tree,int st, int en, int qs, int qe, int ind,long inc) { if(st>qe || en<qs)return ; if(st==en) { tree[ind][0]=inc; return; } int mid=(st+en)/2; update(tree,st,mid,qs,qe,2*ind,inc); update(tree,mid+1,en,qs,qe,2*ind+1,inc); if(tree[2*ind][0]<tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind][0]; tree[ind][1]=tree[2*ind][1]; } if(tree[2*ind][0]>tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind+1][0]; tree[ind][1]=tree[2*ind+1][1]; } if(tree[2*ind][0]==tree[(2*ind)+1][0]) { tree[ind][0]=tree[2*ind][0]; tree[ind][1]=tree[2*ind][1]+tree[2*ind+1][1]; } return ; } //-------------------------------------------------------------- public static void main(String args[]) throws NumberFormatException, IOException ,java.lang.Exception { Reader reader = new Reader(); long mod= 1000000007; // long mod= 998244353; // long[] pow2 =new long[64]; // pow2[0]=1l; // for(int i=1;i<64;i++) //// { ////// pow2[i]=(int) Math.pow(2, i); // pow2[i]=((long)(2)*pow2[i-1]); ////// System.out.println(pow2[i]); //// } BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // int cases=Integer.parseInt(br.readLine()); // int cases=1; int cases=reader.nextInt(); while (cases-->0){ // // long N=reader.nextLong(); // long B=reader.nextLong(); // long X=reader.nextLong(); // long Y=reader.nextLong(); // long D2=reader.nextLong(); // long C=reader.nextLong(); // long W=reader.nextLong(); // long A=reader.nextLong(); // long N=reader.nextLong(); int N=reader.nextInt(); // int M=reader.nextInt(); // int D=reader.nextInt(); // int A=reader.nextInt(); // int B=reader.nextInt(); // int K=reader.nextInt(); // String[] first=br.readLine().split(" "); // int N=Integer.parseInt(first[0]); // int X=Integer.parseInt(first[1]); // int Y=Integer.parseInt(first[3]); // String[] first2=br.readLine().split(" "); // String[] first3=br.readLine().split(" "); // int M=Integer.parseInt(first1[1]); // long K=Long.parseLong(first1[0]); // long X=Long.parseLong(first1[1]); // String s3=br.readLine();String s4=br.readLine(); // char[] s11=s2.toCharArray(); // char[] s12=new char[s11.length]; // long max=Long.MIN_VALUE; // long max=10000000000001l; // int min=Integer.MAX_VALUE; // long min=Inteeg.MAX_VALUE; // int min1=Integer.MAX_VALUE; // int min2=Integer.MAX_VALUE; HashMap<Integer, Long> map=new HashMap<Integer,Long>(); // PriorityQueue<Integer> q = new PriorityQueue<Integer>(); // PriorityQueue<Long> q = new PriorityQueue<Long>(Collections.reverseOrder()); // HashMap<Integer,TreeSet<Integer>> map=new HashMap<Integer,TreeSet<Integer>>(); // HashMap<Long,Long> map=new HashMap<Long,Long>(); // HashMap<String,String> map1=new HashMap<String,String>(); // TreeMap<Long,Integer> map1=new TreeMap<Long,Integer>(); // List<TreeMap<Integer,Integer>> map = new ArrayList<TreeMap<Integer,Integer>>(); // HashSet<Character> set =new HashSet<Character>(); // HashSet<String> set1 =new HashSet<String>(); // HashSet<Integer> map =new HashSet<Integer>(); // HashSet<Long> map =new HashSet<Long>(); // TreeSet<Integer> a =new TreeSet<Integer>(); // TreeSet<Long> b =new TreeSet<Long>(); // TreeSet<Integer> map=new TreeSet<Integer>(); int[] arr=new int[N]; // Integer[] arr=new Integer[N]; // Integer[] arr2=new Integer[N]; // int[] arr2=new int[64]; // int[] ev=new int[N]; // int[] od=new int[N]; // boolean[] s=new boolean[K+1]; // int[] arr=new int[32];// i00nt[] odd=new int[100001]; // Integer[] arr=new Integer[N]; // Integer[] arr1=new Integer[N]; // long[] b=new long[N+1]; // long[] suf=new long[N+1]; // Integer[] arr=new Integer[N]; // Long[] arr=new Long[N]; // long[][] dp=new long[N][M+1]; // ArrayList<String> l=new ArrayList<String>(); for(int i=0;i<N;i++)arr[i]=reader.nextInt(); long[] dp=new long[N]; for(int i=0;i<N-1;i++) { long k=0; for(int j=i+1;j<N;j++) { if(arr[j]<arr[i])k++; } map.put(arr[i], k); for(int j=i+1;j<N;j++) { if(arr[j]<arr[i])k--; dp[j]=dp[j]+(long)k; } } long ans=0; for(int i=0;i<N-1;i++) { long cur=map.get(arr[i]); for(int j=i+1;j<N;j++) { if(arr[j]>arr[i]) { ans=ans+dp[j]-cur; } else cur--; dp[j]=dp[j]-cur; } } System.out.println(ans); } output.flush(); } } // // output.flush(); // output.flush();
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
6f6b58af25fc9ed515295dc6f96ab0b4
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import com.sun.source.tree.Tree; import com.sun.source.util.Trees; import javax.swing.tree.TreeCellRenderer; import java.io.*; import java.util.*; public class B { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007L; static HashMap<String,Integer>map=new HashMap<>(); public static void main(String[] args) { int t=in.nextInt(); StringBuilder res=new StringBuilder(); loop: while(t-->0){ int n=in.nextInt(); int a[]=in.readintarray(n); long ans=0; int f[]=new int[n+1]; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i]>a[j]){ f[i]++; } } } // for(int x: f) // System.out.print(x+" "); // System.out.println(); for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(a[j]>a[i]){ f[j]--; } } //for(int x: f) //System.out.print(x+" "); //System.out.println("---"); int sum[]=new int[n+1]; sum[0]=f[0]; for(int j=1;j<n;j++) sum[j]=f[j]+sum[j-1]; // for(int x: sum) // System.out.print(x+" "); // System.out.println("---"); for(int j=0;j<i;j++){ if(a[j]<a[i]){ // System.out.println(i+" : "+j); ans=ans+sum[i-1]-sum[j]; // System.out.println("ans : "+ans); } } } res.append(ans+"\n"); } System.out.println(res); } static long calculateSum(long n) { if(n<0) { return 0; } return n*(n+1)/2; } static class Node implements Comparable<Node>{ int val; char ch; Node(int x,char y) { val=x; ch=y; } @Override public int compareTo(Node o) { if(val>o.val) { return 1; } if(val==o.val) { return 0; } return -1; } } static int max(int a, int b) { if(a<b) return b; return a; } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static < E > void print(E res) { System.out.println(res); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static int abs(int a) { if(a<0) return -1*a; return a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
1b9c52d7423e283d8b7fa68a28e4bfb4
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.cert.X509CRL; import java.util.*; import java.lang.*; import java.util.stream.Collector; import java.util.stream.Collectors; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; static String OUTPUT = ""; //global private final static long BASE = 998244353L; private final static int INF_I = 1001001001; private final static long INF_L = 1001001001001001001L; private final static int MAXN = 100100; private static int decode(int a, int b) { return a + 2*b; } static void solve() { int ntest = readInt(); for (int test=0;test<ntest;test++) { int N = readInt(); int[] P = readIntArray(N); int[][] F = new int[N][N]; int[][] G = new int[N][N]; for (int b=1;b<N;b++) for (int d=b+2;d<N;d++) if (P[b]>P[d]) G[b][b+1]+=1; long ans=0; for (int c=2;c<N;c++) for (int a=c-1;a>=1;a--) { int b=a; F[a-1][c] = F[a][c] + G[b][c]; if (c+1<N) G[b][c+1] = G[b][c] - ((P[b]>P[c+1])?1:0); if (P[a-1] < P[c]) ans += F[a-1][c]; } out.println(ans); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } if (OUTPUT == "") out = new PrintWriter(System.out); else out = new PrintWriter(OUTPUT); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> { private T x; private T y; public Point(T x, T y) { this.x = x; this.y = y; } public T getX() {return x;} public T getY() {return y;} @Override public int compareTo(Point<T> o) { int cmp = x.compareTo(o.getX()); if (cmp==0) return y.compareTo(o.getY()); return cmp; } } private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> { public ClassComparator() {} @Override public int compare(T a, T b) { return a.compareTo(b); } } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
c236c0b0c896d131a960b52436fc11c5
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class CF789VC { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(int [] a) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i:a) { arr.add(i); } Collections.sort(arr); int len = arr.size(); for(int i=0;i<len;++i) a[i] = arr.get(i); } static class FenwickTreeExample { // Max size of the Fenwick tree in this code static int MAX_SIZE ; // the array that represents the fenwick tree private int fenArr[]; FenwickTreeExample(int n) { MAX_SIZE=n; fenArr = new int [4*MAX_SIZE+15]; for(int i=0;i<4*MAX_SIZE+15;++i) fenArr[i] = 0; } // s --> It is number of element available in the input array. // fenArr[0 ... s] --> The array that represents the Fenwick Tree // a[0 ... s - 1] --> It is the input array for which the prefix sum is generated. // Returns the sum of a[0... idx]. The method assumes // that the array is already preprocessed and // the partial sums of the array elements are kept // in fenArr[]. int getArrSum(int idx) { // Initializing the result to 0 int total = 0; // index in the fenTree[] is one more than the // index in the array a[] idx = idx + 1; // Traversing the ancestors of the fenTree[idx] while(idx > 0) { // Adding the current element of the array fenArr[] // to the total total = total + fenArr[idx]; // Moving the index to the parent node in // getArrSum view idx -= idx & (-idx); } return total; } // Updating a node in the Fenwick Tree // at a given index in the array fenArr[]. The given input value // 'v' is added to the fenArr[idx] and therefore, it is also added to the // ancestors of the tree too. public void updateFenwick(int s, int idx, int v) { // index in the array fenArr[] is 1 more than the // index in the array a[] idx = idx + 1; // Traversing all the ancestors and adding 'v' while(idx <= s) { // Add 'val' to current node of BIT Tree fenArr[idx] = fenArr[idx] + v; // Updating the idx to that of parent // in the update View idx = idx + (idx & (-idx)); } } // Method to build the Fenwick tree // from the given array. void constructFenTree(int arr[], int s) { // Initializing fenArr[] as 0 for(int i = 1; i <= s; i++) { fenArr[i] = 0; } // Storing the original values in the fenArr[] // using the mehtod updateFenwick() for(int j = 0; j < s; j++) { updateFenwick(s, j, arr[j]); } } } public static void main(String[] args) { // TODO Auto-generated method stub PrintWriter out = new PrintWriter(System.out); FastReader fs = new FastReader(); int t = fs.nextInt(); for(int cs=0;cs<t;++cs) { int n = fs.nextInt(); //int [] lesser = new int [n+1]; int [] permutation = new int [n+1]; //int [] suffsum = new int [n+1]; int lastSum = 0; for(int i=1;i<=n;++i) permutation[i] = fs.nextInt(); FenwickTreeExample decreasingComp = new FenwickTreeExample(n+1); // for(int i=1;i<=n;++i) // { // lesser[i] = decreasingComp.compute(1, n, 1, permutation[i], n); // decreasingComp.update(1, n, 1, permutation[i]); // lastSum+=lesser[i]; // suffsum[i] = lastSum; // } //segtree runningseg = new segtree(n); long answer=0; for(int j=n;j>=1;--j) { lastSum=0; for(int k=j-2;k>=1;--k) { lastSum+=decreasingComp.getArrSum(permutation[k+1]-1); if(permutation[k]<permutation[j]) answer+=(long)lastSum; } decreasingComp.updateFenwick(n+1,permutation[j],1); } out.println(answer); } out.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
15d028feaba3afd96ad14b27227d90e4
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int[] permutation = new int[n + 1]; for (int i = 1; i <= n; i++) { permutation[i] = sc.nextInt(); } // count tuples (a, b, c, d) such that (a < b < c < d) and (permutation[a] < permutation[c] && permutation[b] > permutation[d]). int[] pairs = new int[n + 1]; // pairs[i] stores number of pairs (b, d) such that permutation[b] > permutation[d]. for (int b = 1; b <= n; b++) { for (int d = b + 1; d <= n; d++) { if (permutation[b] > permutation[d]) { pairs[b]++; } } } long[] prefix = new long[n + 1]; long tuples = 0; for (int c = 1; c <= n; c++) { for (int b = 1; b < c; b++) { if (permutation[b] > permutation[c]) { // since we want c < d, but pairs[b] would also have d <= c, so removing such bad pairs. pairs[b]--; } } prefix[0] = 0; for (int i = 1; i <= c; i++) { prefix[i] = prefix[i - 1] + pairs[i]; } for (int a = 1; a < c; a++) { if (permutation[a] < permutation[c]) { tuples += prefix[c - 1] - prefix[a]; } } } out.println(tuples); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9d291016947ef76e296f2a6f53cc55fe
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class ComdeFormces { public static int cc2; public static pair pr; public static long sum; public static int ind2; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub // Reader.init(System.in); FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); int t=sc.nextInt(); int tc=1; while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); int l[][]=new int[n][n]; int r[][]=new int[n][n]; for(int i=0;i<n;i++) { int vl=0; for(int j=0;j<i;j++) { if(a[i]>a[j])vl++; l[i][j]=vl; } } for(int i=n-1;i>=0;i--) { int vl=0; for(int j=n-1;j>i;j--) { if(a[i]>a[j])vl++; r[i][j]=vl; } } long ans=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(i-1<0 || j+1>=n)continue; int lft=l[j][i-1]; int rt=r[i][j+1]; ans+=lft*rt; } } log.write(ans+"\n"); log.flush(); } } static int bsfd(ArrayList<Integer> ar,int el) { int s=0; int e=ar.size()-1; while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)<=el)s=m+1; else e=m-1; } return e>=0?e+1:0; } static int find(int el,int p[]) { if(p[el]<0)return el; return p[el]=find(p[el],p); } static boolean find(int a,int b,int p[]) { int p1=find(a,p); int p2=find(b,p); if(p1>=0 && p1==p2)return false; else { if(p[p1]<p[p2]) { p[p1]+=p[p2]; p[p2]=p1; } else { p[p2]+=p[p1]; p[p1]=p2; } return true; } } static long eval(ArrayList<ArrayList<Integer>> ar,int src,long f[], boolean vis[]) { long mn=Integer.MAX_VALUE; vis[src]=true; for(int p:ar.get(src)) { if(!vis[p]) { long s=eval(ar,p,f,vis); mn=Math.min(mn,s); sum+=s; } } if(src==0)return 0; if(mn==Integer.MAX_VALUE)return f[src]; sum-=mn; return Math.max(f[src], mn); } public static void radixSort(int a[]) { int n=a.length; int res[]=new int[n]; int p=1; for(int i=0;i<=8;i++) { int cnt[]=new int[10]; for(int j=0;j<n;j++) { a[j]=res[j]; cnt[(a[j]/p)%10]++; } for(int j=1;j<=9;j++) { cnt[j]+=cnt[j-1]; } for(int j=n-1;j>=0;j--) { res[cnt[(a[j]/p)%10]-1]=a[j]; cnt[(a[j]/p)%10]--; } p*=10; } } static int bits(long n) { int ans=0; while(n!=0) { if((n&1)==1)ans++; n>>=1; } return ans; } static long flor(ArrayList<Long> ar,long el) { int s=0; int e=ar.size()-1; while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)==el)return ar.get(m); else if(ar.get(m)<el)s=m+1; else e=m-1; } return e>=0?e:-1; } public static int kadane(int a[]) { int sum=0,mx=Integer.MIN_VALUE; for(int i=0;i<a.length;i++) { sum+=a[i]; mx=Math.max(mx, sum); if(sum<0) sum=0; } return mx; } public static int m=(int)(1e9+7); public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%m)*(b%m))%m; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } //debug public static <E> void p(E[][] a,String s) { System.out.println(s); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } public static void p(int[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static void p(long[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static <E> void p(E a,String s){ System.out.println(s+"="+a); } public static <E> void p(ArrayList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(LinkedList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(HashSet<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Stack<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Queue<E> a,String s){ System.out.println(s+"="+a); } //utils static ArrayList<Integer> divisors(int n){ ArrayList<Integer> ar=new ArrayList<>(); for (int i=2; i<=Math.sqrt(n); i++){ if (n%i == 0){ if (n/i == i) { ar.add(i); } else { ar.add(i); ar.add(n/i); } } } return ar; } static ArrayList<Integer> prime(int n){ ArrayList<Integer> ar=new ArrayList<>(); int cnt=0; boolean pr=false; while(n%2==0) { ar.add(2); n/=2; } for(int i=3;i*i<=n;i+=2) { pr=false; while(n%i==0) { n/=i; ar.add(i); pr=true; } } if(n>2) ar.add(n); return ar; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long factmod(long n,long mod,long img) { if(n==0)return 1; long ans=1; long temp=1; while(n--!=0) { if(temp!=img) { ans=((ans%mod)*((temp)%mod))%mod; } temp++; } return ans%mod; } static int ncr(int n, int r){ if(r>n-r)r=n-r; int ans=1; for(int i=0;i<r;i++){ ans*=(n-i); ans/=(i+1); } return ans; } public static class trip{ int a,b; int c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } public int compareTo(trip q) { return this.b-q.b; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<=a[ptr2]) { b[i]=a[ptr1]; ptr1++; i++; } else { b[i]=a[ptr2]; ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } public int compareTo(pair b) { return this.a-b.a; } // public int compareToo(pair b) { // return this.b-b.b; // } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
55e86379a103911fbba6611c74bb7fef
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static Scanner obj = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static int i() { return obj.nextInt(); } public static void main(String[] args) { int len = i(); while (len-- != 0) { int n=i(); int[] a=new int[n]; for(int i=0;i<n;i++)a[i]=obj.nextInt(); long res=0; int[] validA_C=new int [n]; for(int i=0;i<n;i++) { long cnt=0; for(int j=i+1;j<n;j++) { if(a[i]>a[j])res+=cnt; cnt+=validA_C[j]; if(a[i]<a[j])validA_C[j]++; } } out.println(res); } out.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
55d8268aaf92739fe8b057ef5ed2d04c
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class StrangeInequality { public static void main(String[] args) throws IOException { // BufferedReader in = new BufferedReader(new FileReader("StrangeInequality.in")); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("StrangeInequality.out"))); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { int N = Integer.parseInt(in.readLine()); int[] a = new int[N]; StringTokenizer st = new StringTokenizer(in.readLine()); for (int i = 0; i < N; i++) { a[i] = Integer.parseInt(st.nextToken()) - 1; } int[][] numLessAfter = new int[N][N]; for (int i = N - 2; i >= 0; i--) { for (int j = 0; j < N; j++) { numLessAfter[i][j] = numLessAfter[i + 1][j] + (a[i + 1] < j ? 1 : 0); } } int[][] numLessBefore = new int[N][N]; for (int i = 1; i < N; i++) { for (int j = 0; j < N; j++) { numLessBefore[i][j] = numLessBefore[i - 1][j] + (a[i - 1] < j ? 1 : 0); } } long ans = 0; for (int i = 1; i < N - 2; i++) { for (int j = i + 1; j < N - 1; j++) { ans += numLessAfter[j][a[i]] * numLessBefore[i][a[j]]; } } out.println(ans); } out.close(); in.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
44fea6335ea304e8a9709fe236104f7a
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// package c1678; // // Codeforces Round #789 (Div. 2) 2022-05-08 07:35 // C. Tokitsukaze and Strange Inequality // https://codeforces.com/contest/1678/problem/C // time limit per test 1.5 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // Tokitsukaze has a permutation p of length n. Recall that a permutation p of length n is a // sequence p_1, p_2, ..., p_n consisting of n distinct integers, each of which from 1 to n (1 <= // p_i <= n). // // She wants to know how many different indices tuples [a,b,c,d] (1 <= a < b < c < d <= n) in this // permutation satisfy the following two inequalities: p_a < p_c and p_b > p_d. // // Note that two tuples [a_1,b_1,c_1,d_1] and [a_2,b_2,c_2,d_2] are considered to be different if // a_1 != a_2 or b_1 != b_2 or c_1 != c_2 or d_1 != d_2. // // Input // // The first line contains one integer t (1 <= t <= 1000)-- the number of test cases. Each test case // consists of two lines. // // The first line contains a single integer n (4 <= n <= 5000)-- the length of permutation p. // // The second line contains n integers p_1, p_2, ..., p_n (1 <= p_i <= n)-- the permutation p. // // It is guaranteed that the sum of n over all test cases does not exceed 5000. // // Output // // For each test case, print a single integer-- the number of different [a,b,c,d] tuples. // // Example /* input: 3 6 5 3 6 1 4 2 4 1 2 3 4 10 5 1 6 2 8 3 4 10 9 7 output: 3 0 28 */ // Note // // In the first test case, there are 3 different [a,b,c,d] tuples. // // p_1 = 5, p_2 = 3, p_3 = 6, p_4 = 1, where p_1 < p_3 and p_2 > p_4 satisfies the inequality, so // one of [a,b,c,d] tuples is [1,2,3,4]. // // Similarly, other two tuples are [1,2,3,6], [2,3,5,6]. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class C1678C { static final int MOD = 998244353; static final Random RAND = new Random(); static long solveB(int[] p) { int n = p.length; // ctl[i] is number of element less than p[i] in [0,i) int[] ctl = new int[n]; int[] ctr = new int[n]; { SegmentTree st = new SegmentTree(n); for (int i = 0; i < n; i++) { ctl[i] = st.sum(0, p[i]); ctr[i] = p[i] - ctl[i]; st.set(p[i], 1); } } long[] presum = new long[n]; for (int i = 0; i < n; i++) { presum[i] = (i == 0 ? 0 : presum[i-1]) + ctl[i]; } long[] sufsum = new long[n]; for (int i = n-1; i >= 0; i--) { sufsum[i] = (i == n-1 ? 0 : sufsum[i+1]) + ctr[i]; } System.out.format(" p:%s\n", Arrays.toString(p)); System.out.format(" ctl:%s\n", Arrays.toString(ctl)); System.out.format(" ctr:%s\n", Arrays.toString(ctr)); System.out.format(" pre:%s\n", Arrays.toString(presum)); System.out.format(" suf:%s\n", Arrays.toString(sufsum)); long nl = presum[n-1]; long nr = sufsum[0]; long nm = 0; for (int i = 0; i < n; i++) { nm += ctl[i] * ctr[i]; } long nlr = 0; for (int i = 1; i < n-1; i++) { nlr += presum[i-1] * sufsum[i+1]; } long ne = 0; for (int i = 0; i < n; i++) { ne += presum[i] * ctr[i]; } System.out.format(" nl:%d nr:%d nm:%d nlr:%d ne:%d\n", nl, nr, nm, nlr, ne); long ans = nl * nr - nm - nlr; return ans; } // Time limit exceeded on pretest 5 static long solve(int[] p) { int n = p.length; FenwickTree st = new FenwickTree(n); st.add(p[0], 1); // 0 1 2 ... n-3 n-2 n-1 // ^ ^ long ans = 0; for (int b = 1; b <= n - 3; b++) { int ctd = p[n-1] < p[b] ? 1 : 0; for (int c = n - 2; c > b; c--) { // * * * * ... * * * * * // ^ ^ // b c int cta = st.sum(p[c]); ans += cta * ctd; if (p[c] < p[b]) { ctd++; } } st.add(p[b], 1); } return ans; } static class FenwickTree { private int[] arr; private final int n; public FenwickTree(int n) { this.n = n; this.arr = new int[n + 1]; } static int next(int idx) { // round up the last section of 1s, for example: // 10110 -> 10110 + 11...101010 & 10110 = 10110 + 10 = 11000 return idx + (-idx & idx); } static int parent(int idx) { // Trim the last 1 return idx - (-idx & idx); } // Increase value at index by delta public void add(int index, int delta) { index++; while (index <= n) { arr[index] += delta; index = next(index); } } // get sum of elements arr[0..index], inclusive. index < n (size - 1) public int sum(int index) { index = Math.min(index, n - 1); index++; int ans = 0; while (index > 0) { ans += arr[index]; index = parent(index); } return ans; } } static class SegmentTree { int m; int[] arr; public SegmentTree(int n) { // smallest power of 2 >= n this.m = 1; while (m < n) { m <<= 1; } arr = new int[m * 2]; } public SegmentTree(int[] nums) { this(nums.length); for (int i = 0; i < nums.length; i++) { set(i, nums[i]); } } public int get(int index) { return arr[m + index]; } public void set(int index, int v) { add(index, v - get(index)); } public void add(int index, int v) { int i = m + index; while (i > 0) { arr[i] += v; i /= 2; } } public int sum(int b, int e) { if (b == e) { return arr[m + b]; } int ib = m + b; int ie = m + e; int vb = arr[ib]; int ve = arr[ie]; while (ib / 2 != ie / 2) { if (ib % 2 == 0) { // If ib is left child of its parent, include the value of its right sibling vb += arr[ib + 1]; } if (ie % 2 == 1) { // If ib is left child of its parent, include the value of its right sibling ve += arr[ie - 1]; } ib /= 2; ie /= 2; } return vb + ve; } } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } long ans = solve(p); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
669a4f5d59dcd9cfb5df3051bb5817b2
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static StringBuilder sb; static dsu dsu; static long fact[]; static int mod = (int) (1e9 + 7); static void solve() { int n=i(); int[]arr=new int[n]; for(int i=0;i<n;i++)arr[i]=i(); int[][]count=new int[n][n]; for(int i=0;i<n;i++){ int v=0; for(int j=0;j<n;j++){ if(arr[j]==i+1){ v++; } count[j][i]=v; } } int[][]less=new int [n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(j==0) { less[i][j]=0; } else{ less[i][j]=less[i][j-1]+count[i][j-1]; } } } long ans=0; for(int b=1;b<n;b++){ for(int c=b+1;c<n;c++){ int v1=arr[b]; int v2=arr[c]; long a1= less[b-1][v2-1]; long a2=less[n-1][v1-1]-less[c][v1-1]; ans+=(a1*a2); } } sb.append(ans+"\n"); } public static void main(String[] args) { sb = new StringBuilder(); int test = i(); fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++) { fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod; } while (test-- > 0) { solve(); } System.out.println(sb); } //**************NCR%P****************** static long ncr(int n, int r) { if (r > n) return (long) 0; long res = fact[n] % mod; // System.out.println(res); res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod; res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod; // System.out.println(res); return res; } static long p(long x, long y)// POWER FXN // { if (y == 0) return 1; long res = 1; while (y > 0) { if (y % 2 == 1) { res = (res * x) % mod; y--; } x = (x * x) % mod; y = y / 2; } return res; } //**************END****************** // *************Disjoint set // union*********// static class dsu { int parent[]; dsu(int n) { parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; } int find(int a) { if (parent[a] ==a) return a; else { int x = find(parent[a]); parent[a] = x; return x; } } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; parent[b] = a; } } //**************PRIME FACTORIZE **********************************// static TreeMap<Integer, Integer> prime(long n) { TreeMap<Integer, Integer> h = new TreeMap<>(); long num = n; for (int i = 2; i <= Math.sqrt(num); i++) { if (n % i == 0) { int nt = 0; while (n % i == 0) { n = n / i; nt++; } h.put(i, nt); } } if (n != 1) h.put((int) n, 1); return h; } //****CLASS PAIR ************************************************ static class Pair implements Comparable<Pair> { int x; long y; Pair(int x, long y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return (int) (this.y - o.y); } } //****CLASS PAIR ************************************************** static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); public static long[] sort(long[] a2) { int n = a2.length; ArrayList<Long> l = new ArrayList<>(); for (long i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static char[] sort(char[] a2) { int n = a2.length; ArrayList<Character> l = new ArrayList<>(); for (char i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static long pow(long x, long y) { long res = 1; while (y > 0) { if (y % 2 != 0) { res = (res * x);// % modulus; y--; } x = (x * x);// % modulus; y = y / 2; } return res; } //GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } // ******LOWEST COMMON MULTIPLE // ********************************************* public static long lcm(long x, long y) { return (x * (y / gcd(x, y))); } //INPUT PATTERN******************************************************** public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } public static int[] readArrayi(int n) { int A[] = new int[n]; for (int i = 0; i < n; i++) { A[i] = i(); } return A; } public static long[] readArray(long n) { long A[] = new long[(int) n]; for (int i = 0; i < n; i++) { A[i] = l(); } return A; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
a96d000786ef6441b2512ac3da34d962
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { var sc = new Scanner(System.in); var pw = new PrintWriter(System.out); int T = Integer.parseInt(sc.next()); for(int t = 0; t < T; t++){ int n = Integer.parseInt(sc.next()); var p = new int[n]; for(int i = 0; i < n; i++){ p[i] = Integer.parseInt(sc.next()); } var bd = new int[n][n]; for(int i = 0; i < n-1; i++){ if(p[i] > p[n-1]){ bd[i][n-1] = 1; } for(int j = n-2; j > i; j--){ if(p[i] > p[j]){ bd[i][j] = bd[i][j+1] + 1; }else{ bd[i][j] = bd[i][j+1]; } } } var ac = new int[n][n]; for(int i = 1; i < n; i++){ if(p[0] < p[i]){ ac[i][0] = 1; } for(int j = 1; j < i; j++){ if(p[j] < p[i]){ ac[i][j] = ac[i][j-1] + 1; }else{ ac[i][j] = ac[i][j-1]; } } } long ans = 0; for(int b = 1; b < n; b++){ for(int c = b+1; c < n-1; c++){ ans += bd[b][c+1] * ac[c][b-1]; } } pw.println(ans); } pw.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b5d58102ce1ed8e8e721f2ffe4c77fae
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public static void main(String[] args) { in = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); try { int t = in.nextInt(); while(t-- > 0) { solve(); out.println();} // solve(); } finally { out.close(); } return; } public static void solve() { int n = in.nextInt(); int[] p = fillArray(n); long ans = 0; int[][] prefix = new int[n+1][n+1]; for(int el = 1; el <= n; el++) { for(int i = 1; i <= n; i++) { prefix[el][i] += prefix[el][i-1]; if(p[i - 1] < el) { prefix[el][i]++; } } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { int b = p[i]; int c = p[j]; int smallerThanB = prefix[b][n] - prefix[b][j+1]; // from (j+1) ... int smallerThanC = prefix[c][i]; ans += smallerThanB * smallerThanC; } } out.print(ans); } //-------------- Helper methods------------------- public static int[] fillArray(int n) { int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = in.nextInt(); } return array; } public static char[] fillArray() { char[] array = in.next().toCharArray(); return array; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static MyScanner in; //-----------MyScanner class for faster input----------x§x public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void shuffleArray(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } //-------------------------------------------------------- }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
e8047e569d7978d4dbd1cfe87bc177da
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Random; public final class C { private static final class BIT { private final int n; private final long[] data; private BIT(int n) { this.n = n; data = new long[n + 1]; } public void add(int idx, long val) { for (int i = idx + 1; i <= n; i += lsb(i)) { data[i] += val; } } public long sum(int l, int r) { return sum(r) - sum(l - 1); } private long sum(int idx) { long res = 0; for (int i = idx + 1; i > 0; i -= lsb(i)) { res += data[i]; } return res; } private static int lsb(int i) { return i & -i; // zeroes all the bits except the least significant one } // get k-th element public int getKth(int k) { int lo = 0; int hi = n; while (lo < hi) { final int mid = lo + hi >>> 1; if (k > sum(mid)) { lo = mid + 1; } else { hi = mid; } } return lo; } } public static void main(String[] args) throws IOException { final FastReader fs = new FastReader(); final int t = fs.nextInt(); for (int test = 0; test < t; test++) { final int n = fs.nextInt(); final int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = fs.nextInt() - 1; } long res = 0; for (int a = 0; a < n - 3; a++) { final BIT bit = new BIT(n); final BIT bdCount = new BIT(n); long bd = 0; for (int v = a + 2; v < n; v++) { bit.add(arr[v], 1); } for (int c = a + 2; c < n - 1; c++) { bdCount.add(arr[c - 1], 1); bd += bit.sum(arr[c - 1]) - bdCount.sum(arr[c], n - 1); bit.add(arr[c], -1); if (arr[a] < arr[c]) { res += bd; } } } System.out.println(res); } } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public int[] nextIntArray(int n) throws IOException { final int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long[] nextLongArray(int n) throws IOException { final long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
4ce2730254fcc6b22e26f30016656353
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class CF1678C extends PrintWriter { CF1678C() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1678C o = new CF1678C(); o.main(); o.flush(); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] pp = new int[n]; for (int i = 0; i < n; i++) pp[i] = sc.nextInt(); int[] kk = new int[n + 1]; int[][] abc = new int[n][n]; for (int b = 0; b < n; b++) { Arrays.fill(kk, 0); for (int a = 0; a < b; a++) { int x = pp[a]; kk[x]++; } for (int x = 1; x <= n; x++) kk[x] += kk[x - 1]; for (int c = b + 1; c < n; c++) { int x = pp[c] - 1; abc[b][c] = kk[x]; } } int[][] bcd = new int[n][n]; for (int c = n - 1; c >= 0; c--) { Arrays.fill(kk, 0); for (int d = n - 1; d > c; d--) { int x = pp[d]; kk[x]++; } for (int x = 1; x <= n; x++) kk[x] += kk[x - 1]; for (int b = c - 1; b >= 0; b--) { int x = pp[b] - 1; bcd[b][c] = kk[x]; } } long ans = 0; for (int b = 0; b < n; b++) for (int c = b + 1; c < n; c++) ans += abc[b][c] * bcd[b][c]; println(ans); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
615f129a6262b0a1ae6eacf1fe5d8ac0
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solutions { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int testCases = Integer.parseInt(br.readLine()); while(testCases-->0){ int n=Integer.parseInt(br.readLine()); String input[]=br.readLine().split(" "); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(input[i]); } int lower[][]=new int[n][n]; int upper[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=i-1;j>=0;j--) { if(arr[j]<arr[i]) { lower[i][j]=1+lower[i][j+1]; }else lower[i][j]=lower[i][j+1]; } } for(int i=n-1;i>=0;i--) { for(int j=i+1;j<n;j++) { if(arr[i]>arr[j]) upper[i][j]=1+upper[i][j-1]; else upper[i][j]=upper[i][j-1]; } } long total=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { total+=(lower[j][0]-lower[j][i])*(upper[i][n-1]-upper[i][j]); } } out.println(total); } out.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
441530642347cf637c121431fa9e5a4f
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
//Utilities import java.io.*; import java.util.*; public class a { static int t; static int n; static int[] a; static int[][] dec, sfa; static long res; public static void main(String[] args) throws IOException { t = in.iscan(); while (t-- > 0) { n = in.iscan(); a = new int[n]; dec = new int[n][n]; sfa = new int[n+1][n+1]; for (int i = 0; i < n; i++) { a[i] = in.iscan(); } for (int i = n-1; i >= 0; i--) { for (int j = i+1; j < n; j++) { dec[i][j] = dec[i][j-1]; if (a[i] > a[j]) { dec[i][j]++; } sfa[i][j] = dec[i][j] + sfa[i+1][j]; } } res = 0; for (int i = 0; i < n-2; i++) { for (int j = i+2; j < n; j++) { if (a[i] < a[j]) { res += (sfa[i+1][n-1] - sfa[j][n-1]) - (sfa[i+1][j] - sfa[j][j]); // for (int k = i+1; k < j; k++) { // res += dec[k][n-1] - dec[k][j]; // } } } } out.println(res); } out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
4d9e98364fc4c28a1bccbba683c19330
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class TaskC { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); TaskC s = new TaskC(); s.solve(in, out); out.flush(); } void solveOne(FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } long[][] b = new long[n][n]; for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < n; j++) { b[i][j] = (a[j] > a[i] ? 1L : 0L); if (i < n - 1) { b[i][j] += b[i + 1][j]; } } } for (int i = 0; i < n; i++) { for (int j = 1; j < n; j++) { b[i][j] += b[i][j - 1]; } } long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 2; j < n - 1; j++) { if (a[i] < a[j]) { long rangeSum = b[j + 1][j - 1] - b[j + 1][i]; ans += rangeSum; } } } out.println(ans); } void solve(FastScanner in, PrintWriter out) { int t = 1; t = in.nextInt(); for (int tc = 1; tc <= t; tc++) { // out.printf("Case #%d: ", tc); solveOne(in, out); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
46ed7fe7d73132f8a76bb00792b929d0
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CTokitsukazeAndStrangeInequality solver = new CTokitsukazeAndStrangeInequality(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CTokitsukazeAndStrangeInequality { int n; int[] arr; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); arr = in.nextIntArray(n); long[][] dp = new long[n][n]; for (int i = n - 2; i >= 1; i--) { FenwickTree f = new FenwickTree(n + 1); for (int j = n - 1; j >= i; j--) { f.add(arr[j], 1); if (arr[i] != 1) dp[i][j] = f.find(1, arr[i] - 1); dp[i][j] += dp[i + 1][j]; } } long ans = 0; for (int a = 0; a < n - 1; a++) { for (int c = a + 2; c < n - 1; c++) { if (arr[c] <= arr[a]) continue; // out.println(a,c,dp[a+1][c+1]-dp[c][c+1]); ans += dp[a + 1][c + 1] - dp[c][c + 1]; } } out.println(ans); } class FenwickTree { public int[] tree; public int size; public FenwickTree(int size) { this.size = size; tree = new int[size + 5]; } public void add(int i, int v) { while (i <= size) { tree[i] += v; i += i & -i; } } public int find(int i) { int res = 0; while (i >= 1) { res += tree[i]; i -= i & -i; } return res; } public int find(int l, int r) { return find(r) - find(l - 1); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
10fd494afc95c8be874b23e172f9e68d
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = sc.nextInt(); while (test-- > 0) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int[][] barr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = n - 1; j > i; j--) { if (arr[i] > arr[j]) { if (j < n - 1) barr[i][j] = barr[i][j + 1] + 1; else barr[i][j] = 1; } else { if (j < n - 1) barr[i][j] = barr[i][j + 1]; } } } for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { barr[i][j] += barr[i - 1][j]; } } // System.out.println(Arrays.deepToString(barr)); long ans = 0; for (int i = 0; i < n-1; i++) { for (int j = i + 2; j < n-1; j++) { if (arr[i] < arr[j]) { ans += (barr[j - 1][j + 1] - barr[i][j + 1]); } } } System.out.println(ans); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
90a9bcbe1fdbafb87148e9e315ca62c5
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { static long[] fac; public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); /* // Do not delete this // Uncomment this before using nCrModPFermat fac = new long[200000 + 1]; fac[0] = 1; for (int i = 1; i <= 200000; i++) fac[i] = (fac[i - 1] * i % 1000000007); */ int te = Reader.nextInt(); // int te = 1; while(te-->0) { int n = Reader.nextInt(); int[] arr = new int[n]; for(int i = 0;i<n;i++){ arr[i] = Reader.nextInt(); } int[][] mat1 = new int[n][n]; int[][] mat2 = new int[n][n]; for(int i = 0;i<n;i++){ for(int j = n-1;j>i;j--){ if(j==n-1){ if(arr[j]<arr[i]){ mat1[i][j]++; } } else{ if(arr[j]<arr[i]){ mat1[i][j] = mat1[i][j+1]+1; } else{ mat1[i][j] = mat1[i][j+1]; } } } } for(int i = 0;i<n;i++){ for(int j = 0;j<i;j++){ if(j==0){ if(arr[j]<arr[i]){ mat2[i][j]++; } } else{ if(arr[j]<arr[i]){ mat2[i][j] = mat2[i][j-1]+1; } else{ mat2[i][j] = mat2[i][j-1]; } } } } long ans = 0; for(int b = 1;b<n;b++){ for(int c = b+1;c<n-1;c++){ ans += (long)mat1[b][c+1]*mat2[c][b-1]; // System.out.println((long)mat1[b][c+1]*mat2[c][b-1]); } } output.write(ans+"\n"); } output.close(); } public static boolean isP(int n){ StringBuilder s1 = new StringBuilder(n+""); StringBuilder s2 = new StringBuilder(n+""); s2.reverse(); for(int i = 0;i<s1.length();i++){ if(s1.charAt(i)!=s2.charAt(i)) return false; } return true; } public static long[] factorial(int n){ long[] factorials = new long[n+1]; factorials[0] = 1; factorials[1] = 1; for(int i = 2;i<=n;i++){ factorials[i] = (factorials[i-1]*i); } return factorials; } public static long numOfBits(long n){ long ans = 0; while(n>0){ n = n & (n-1); ans++; } return ans; } public static long ceilOfFraction(long x, long y){ // ceil using integer division: ceil(x/y) = (x+y-1)/y // using double may go out of range. return (x+y-1)/y; } public static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p public static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. public static long nCrModPFermat(int n, int r, int p) { if (n<r) return 0; if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long ncr(long n, long r) { long p = 1, k = 1; if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; long m = gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } public static boolean isPrime(long n){ if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; (long) i * i <= n; i = i + 6){ if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } public static int powOf2JustSmallerThanN(int n) { n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return n ^ (n >> 1); } public static long merge(int[] arr, int[] aux, int low, int mid, int high) { int k = low, i = low, j = mid + 1; long inversionCount = 0; // while there are elements in the left and right runs while (i <= mid && j <= high) { if (arr[i] <= arr[j]) { aux[k++] = arr[i++]; } else { aux[k++] = arr[j++]; inversionCount += (mid - i + 1); // NOTE } } // copy remaining elements while (i <= mid) { aux[k++] = arr[i++]; } /* no need to copy the second half (since the remaining items are already in their correct position in the temporary array) */ // copy back to the original array to reflect sorted order for (i = low; i <= high; i++) { arr[i] = aux[i]; } return inversionCount; } // Sort array `arr[low…high]` using auxiliary array `aux` public static long mergesort(int[] arr, int[] aux, int low, int high) { if (high <= low) { // if run size <= 1 return 0; } int mid = (low + ((high - low) >> 1)); long inversionCount = 0; // recursively split runs into two halves until run size <= 1, // then merges them and return up the call chain // split/merge left half inversionCount += mergesort(arr, aux, low, mid); // split/merge right half inversionCount += mergesort(arr, aux, mid + 1, high); // merge the two half runs inversionCount += merge(arr, aux, low, mid, high); return inversionCount; } public static void reverseArray(int[] arr,int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static long gcd(long a, long b){ if(a==0){ return b; } return gcd(b%a,a); } public static long lcm(long a, long b){ if(a>b) return a/gcd(b,a) * b; return b/gcd(a,b) * a; } public static long largeExponentMod(long x,long y,long mod){ // computing (x^y) % mod x%=mod; long ans = 1; while(y>0){ if((y&1)==1){ ans = (ans*x)%mod; } x = (x*x)%mod; y = y >> 1; } return ans; } public static boolean[] numOfPrimesInRange(long L, long R){ boolean[] isPrime = new boolean[(int) (R-L+1)]; Arrays.fill(isPrime,true); long lim = (long) Math.sqrt(R); for (long i = 2; i <= lim; i++){ for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){ isPrime[(int) (j - L)] = false; } } if (L == 1) isPrime[0] = false; return isPrime; } public static ArrayList<Long> primeFactors(long n){ ArrayList<Long> factorization = new ArrayList<>(); if(n%2==0){ factorization.add(2L); } while(n%2==0){ n/=2; } if(n%3==0){ factorization.add(3L); } while(n%3==0){ n/=3; } if(n%5==0){ factorization.add(5L); } while(n%5==0){ // factorization.add(5L); n/=5; } int[] increments = {4, 2, 4, 2, 4, 6, 2, 6}; int i = 0; for (long d = 7; d * d <= n; d += increments[i++]) { if(n%d==0){ factorization.add(d); } while (n % d == 0) { // factorization.add(d); n /= d; } if (i == 8) i = 0; } if (n > 1) factorization.add(n); return factorization; } } class DSU { int[] size, parent; int n; public DSU(int n){ this.n = n; size = new int[n]; parent = new int[n]; for(int i = 0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int u){ if(parent[u]==u){ return u; } return parent[u] = find(parent[u]); } public void merge(int u, int v){ u = find(u); v = find(v); if(u!=v){ if(size[u]>size[v]){ parent[v] = u; size[u] += size[v]; } else{ parent[u] = v; size[v] += size[u]; } } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
7755cc6f79de8ae68ddacf1d2d69272a
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int [] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } long [][] memo = new long[n][n]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (j > 0) memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } for (int j = i+1; j < n; j++) { memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } } long ans = 0; for (int i = 1; i < n-2; i++) { // left for (int j = i+1; j < n-1; j++) { // right ans += (memo[j][i-1] * (memo[i][n-1] - memo[i][j])); } } System.out.println(ans); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } int[] sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i : arr) list.add(i); Collections.sort(list); int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = list.get(i); return res; } void debug(int a) { System.out.println("This is var " + a); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5319fd5948a346c84394de9e3f5c9335
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { // Graph // prefix sums //inputs public static void main(String args[])throws Exception{ Input sc=new Input(); precalculates p=new precalculates(); StringBuilder sb=new StringBuilder(); int t=sc.readInt(); for(int f=0;f<t;f++){ int n=sc.readInt(); int a[]=sc.readArray(); int dpa[][]=new int[n+1][n+1]; int dpb[][]=new int[n+1][n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(a[j-1]<i) dpa[i][j]=dpa[i][j-1]+1; else dpa[i][j]=dpa[i][j-1]; if(a[j-1]>i) dpb[i][j]=dpb[i][j-1]+1; else dpb[i][j]=dpb[i][j-1]; } } // for(int i=0;i<=n;i++){ // for(int j=0;j<=n;j++){ // System.out.print(dpa[i][j]+" "); // } // System.out.println(); // } // System.out.println("----------------"); // for(int i=0;i<=n;i++){ // for(int j=0;j<=n;j++){ // System.out.print(dpb[i][j]+" "); // } // System.out.println(); // } long count=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ count+=dpa[a[j]][i]*(dpa[a[i]][n]-dpa[a[i]][j+1]); } } sb.append(count+"\n"); } System.out.print(sb); } } class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } return a; } } class precalculates{ public long gcd(long p, long q) { if (q == 0) return p; else return gcd(q, p % q); } public int[] prefixSumOneDimentional(int a[]){ int n=a.length; int dp[]=new int[n]; for(int i=0;i<n;i++){ if(i==0) dp[i]=a[i]; else dp[i]=dp[i-1]+a[i]; } return dp; } public int[] postSumOneDimentional(int a[]) { int n = a.length; int dp[] = new int[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) dp[i] = a[i]; else dp[i] = dp[i + 1] + a[i]; } return dp; } public int[][] prefixSum2d(int a[][]){ int n=a.length;int m=a[0].length; int dp[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; } } return dp; } public long pow(long a,long b){ long mod=998244353; long ans=1; if(b<=0) return 1; if(b%2==0){ ans=pow(a,b/2)%mod; return ((ans%mod)*(ans%mod))%mod; }else{ ans=pow(a,b-1)%mod; return ((a%mod)*(ans%mod))%mod; } } } class GraphInteger{ HashMap<Integer,vertex> vtces; class vertex{ HashMap<Integer,Integer> children; public vertex(){ children=new HashMap<>(); } } public GraphInteger(){ vtces=new HashMap<>(); } public void addVertex(int a){ vtces.put(a,new vertex()); } public void addEdge(int a,int b,int cost){ if(!vtces.containsKey(a)){ vtces.put(a,new vertex()); } if(!vtces.containsKey(b)){ vtces.put(b,new vertex()); } vtces.get(a).children.put(b,cost); // vtces.get(b).children.put(a,cost); } public boolean isCyclicDirected(){ boolean isdone[]=new boolean[vtces.size()+1]; boolean check[]=new boolean[vtces.size()+1]; for(int i=1;i<=vtces.size();i++) { if (!isdone[i] && isCyclicDirected(i,isdone, check)) { return true; } } return false; } private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){ if(check[i]) return true; if(isdone[i]) return false; check[i]=true; isdone[i]=true; Set<Integer> set=vtces.get(i).children.keySet(); for(Integer ii:set){ if(isCyclicDirected(ii,isdone,check)) return true; } check[i]=false; return false; } } class union_find { int n; int[] sz; int[] par; union_find(int nval) { n = nval; sz = new int[n + 1]; par = new int[n + 1]; for (int i = 0; i <= n; i++) { par[i] = i; sz[i] = 1; } } int root(int x) { if (par[x] == x) return x; return par[x] = root(par[x]); } boolean find(int a, int b) { return root(a) == root(b); } int union(int a, int b) { int ra = root(a); int rb = root(b); if (ra == rb) return 0; if(a==b) return 0; if (sz[a] > sz[b]) { int temp = ra; ra = rb; rb = temp; } par[ra] = rb; sz[rb] += sz[ra]; return 1; } } /* static int mod=998244353; private static int add(int x, int y) { x += y; return x % MOD; } private static int mul(int x, int y) { int res = (int) (((long) x * y) % MOD); return res; } private static int binpow(int x, int y) { int z = 1; while (y > 0) { if (y % 2 != 0) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } private static int inv(int x) { return binpow(x, MOD - 2); } private static int devide(int x, int y) { return mul(x, inv(y)); } private static int C(int n, int k, int[] fact) { return devide(fact[n], mul(fact[k], fact[n-k])); } */
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
5f87fbbaa789d075ac455d9eda63fa61
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main (String[] args) throws IOException { Kattio io = new Kattio(); int t = io.nextInt(); for (int ii=0; ii<t; ii++) { int n = io.nextInt(); int[][] psum = new int[n+1][n+1]; int[][] back_psum = new int[n+1][n+1]; int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = io.nextInt(); } for (int i=0; i<n; i++) { int x = arr[i]; for (int j=1; j<=n; j++) { if (j > x) { psum[j][i+1] = psum[j][i] + 1; } else { psum[j][i+1] = psum[j][i]; } } } for (int i=n-1; i>=0; i--) { int x = arr[i]; for (int j=1; j<=n; j++) { if (j > x) back_psum[j][i] = back_psum[j][i + 1] + 1; else back_psum[j][i] = back_psum[j][i+1]; } } /*for (int i=0; i<=n; i++) { System.out.print("i:" + i + " "); for (int j=0; j<=n; j++) { System.out.print(psum[i][j] + " "); } System.out.println(); } System.out.println("backpsum:"); for (int i=0; i<=n; i++) { System.out.print("i:" + i + " "); for (int j=0; j<=n; j++) { System.out.print(back_psum[i][j] + " "); } System.out.println(); }*/ long ans = 0; for (int b=0; b<n; b++) { for (int c=b+1; c<n; c++) { int left = b; int right = n - 1 - c; ans += (psum[arr[c]][left] * back_psum[arr[b]][n - right]); } } System.out.println(ans); } } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
1dfb9450d5e55b6e913da6e4d95727f7
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void main(String[]args){ long s = System.currentTimeMillis(); new Solver().run(); System.err.println(System.currentTimeMillis()-s+"ms"); } } class Solver{ final long mod = (long)1e9+7l; final boolean DEBUG = true, MULTIPLE_TC = true; FastReader sc; PrintWriter out; int N, arr[], pref[][], suff[][]; void init(){ N = ni(); arr = new int[N + 1]; for(int i = 1; i <= N; i++){ arr[i] = ni(); } pref = new int[N + 2][N + 2]; suff = new int[N + 2][N + 2]; for(int i = 1; i <= N; i++){ pref[i] = pref[i - 1].clone(); pref[i][arr[i]] += 1; } for(int i = N; i >= 1; i--){ suff[i] = suff[i + 1].clone(); suff[i][arr[i]] += 1; } for(int i = 1; i <= N; i++){ createPrefArr(i, pref); createPrefArr(i, suff); } } void createPrefArr(int idx, int ar[][]){ int a[] = ar[idx]; for(int i = 1; i <= N; i++){ a[i] += a[i - 1]; } } int findElementsInRangeAndAfterGivenIdx(int idx, int l, int r){ if(l > r){ return 0; } int a[] = suff[idx + 1]; int ret = a[r] - a[l - 1]; return ret; } int findElementsInRangeAndBeforeGivenIdx(int idx, int l, int r){ if(l > r){ return 0; } int a[] = pref[idx - 1]; int ret = a[r] - a[l - 1]; return ret; } void process(int testNumber){ init(); long res = 0l; for(int i = 2; i <= N; i++){ int b = arr[i]; for(int j = i + 1; j < N; j++){ int c = arr[j]; long x = findElementsInRangeAndBeforeGivenIdx(i, 1, c - 1), y = findElementsInRangeAndAfterGivenIdx(j, 1, b - 1); res += (x * y); } } pn(res); } void run(){ sc = new FastReader(); out = new PrintWriter(System.out); int t = MULTIPLE_TC ? ni() : 1; for(int test = 1; test <= t; test++){ process(test); } out.flush(); } void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); }; void pn(Object o){ out.println(o); } void p(Object o){ out.print(o); } int ni(){ return Integer.parseInt(sc.next()); } long nl(){ return Long.parseLong(sc.next()); } double nd(){ return Double.parseDouble(sc.next()); } String nln(){ return sc.nextLine(); } long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class pair implements Comparable<pair> { int first, second; public pair(int first, int second){ this.first = first; this.second = second; } @Override public int compareTo(pair ob){ if(this.first != ob.first) return this.first - ob.first; return this.second - ob.second; } @Override public String toString(){ return this.first + " " + this.second; } static public pair from(int f, int s){ return new pair(f, s); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
8e5f975df591b051828874f6f39bdfb3
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// Java is like Alzheimer's, it starts off slow, but eventually, your memory is gone. import java.io.*; import java.util.*; public class Aqueous { static MyScanner sc = new MyScanner(); static PrintWriter pw = new PrintWriter(System.out); static class pair{ int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } } public static void main(String[] args) { int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i=0; i<n;i++) { a[i] = sc.nextInt(); } int bd[][] = new int[n][n]; for(int i =0; i<n-1; i++) { if(a[n-1]<a[i]) { bd[i][n-1] =1; } for(int j = n-2; j>i; j--) { bd[i][j]+=bd[i][j+1]; if(a[j]<a[i]) { bd[i][j]++; } } } int ac[][] = new int[n][n]; for(int i =1; i<n; i++) { if(a[0]<a[i]) { ac[i][0] = 1; } for(int j = 1; j<i; j++) { ac[i][j]+=ac[i][j-1]; if(a[j]<a[i]) { ac[i][j]++; } } } long ans = 0; for(int b = 1; b<n-2; b++) { for(int c = b+1; c<n-1; c++) { ans += bd[b][c+1]*ac[c][b-1]; } } pw.println(ans); } pw.close(); } static void ruffleSort(int a[]) { int n = a.length; Random r = new Random(); for (int i = 0; i < n; i++) { int oi = r.nextInt(n); int temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSort(long a[]) { int n = a.length; Random r = new Random(); for (int i = 0; i < n; i++) { int oi = r.nextInt(n); long temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
d562fe168562922899265059c562fdcb
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out); FastScanner fs = new FastScanner(); int ti = fs.nextInt(); outer: while (ti-- > 0) { int n = fs.nextInt(); int[] a = fs.readArray(n); int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (j - 1 >= 0) dp[i][j] = dp[i][j - 1] + ((a[j] < a[i]) ? 1 : 0); else dp[i][j] = ((a[j] < a[i]) ? 1 : 0); } for (int j = n - 1; j > i; j--) { if (j + 1 < n) dp[i][j] = dp[i][j + 1] + ((a[j] < a[i]) ? 1 : 0); else dp[i][j] = ((a[j] < a[i]) ? 1 : 0); } } long ans = 0; for (int i = 1; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { ans += (dp[j][i - 1] * dp[i][j + 1]); } } out.println(ans); } out.close(); } static final int mod = 1_000_000_007; static void sort(long[] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int oi = random.nextInt(n); long temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static void sort(int[] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { return ((a - b) % mod + mod) % mod; } static long mul(long a, long b) { return (a * b) % mod; } static long exp(long base, long exp) { if (exp == 0) return 1; long half = exp(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials = new long[2_000_001]; static long[] invFactorials = new long[2_000_001]; static void precompFacts() { factorials[0] = invFactorials[0] = 1; for (int i = 1; i < factorials.length; i++) factorials[i] = mul(factorials[i - 1], i); invFactorials[factorials.length - 1] = exp(factorials[factorials.length - 1], mod - 2); for (int i = invFactorials.length - 2; i >= 0; i--) invFactorials[i] = mul(invFactorials[i + 1], i + 1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n - k])); } static boolean isPrime(int n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if (b % 2 == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static int divCount(int n) { boolean hash[] = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class Pair { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
b4b3ccbb17958da095d15a6d8aa82cd3
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int [] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } long [][] memo = new long[n][n]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (j > 0) memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } for (int j = i+1; j < n; j++) { memo[i][j] = memo[i][j-1]; if(arr[i] > arr[j]) memo[i][j]++; } } long ans = 0; for (int i = 1; i < n-2; i++) { // left for (int j = i+1; j < n-1; j++) { // right ans += (memo[j][i-1] * (memo[i][n-1] - memo[i][j])); } } System.out.println(ans); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } int[] sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i : arr) list.add(i); Collections.sort(list); int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = list.get(i); return res; } void debug(int a) { System.out.println("This is var " + a); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
258f6282494abb3cfb221ced1577bb23
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
//package com.company; import java.math.BigInteger; import java.util.*; import java.lang.*; import java.io.*; public class Main { public static FastScanner fs = new FastScanner(); public static Scanner sc = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static int inf = 1000000007; public static BigInteger infb = new BigInteger("1000000007"); public static long lmax= (long) 1e18; public static boolean flag=false; public static StringBuilder sb=new StringBuilder(); /////// For printing elements in 1D-array public static long[] arr = new long[5009]; public static int ww[][]=new int[5009][5009]; public static int ss[][]=new int[5009][5009]; public static void print1d(long[] arr) { for (long x : arr) { out.print(x + " "); } out.println(); } /////// For printing elements in 2D-array public static void print2d(long[][] arr) { for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[0].length;j++){ out.print(arr[i][j]+" "); } out.println(); } out.println(); } /////// For freq of elements in array public static long[] freq(long[] freq_arr, long[] arr) { for (long j : arr) { freq_arr[(int) j]++; } return freq_arr; } /////// For sum elements in array public static long sum(long[] arr) { long sum = 0; for (int i=0;i<arr.length;i++) { sum += arr[i]; } return sum; } /////// For storing elements in array 1D public static long[] scan1d(long[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] = fs.nextLong(); } return arr; } /////// For storing elements in array 2D public static long[][] scan2d(long[][] arr) { for (int i = 0; i < arr.length; i++) { arr[i][0] = fs.nextLong(); arr[i][1] = fs.nextLong(); } return arr; } /////// For copying elements in array public static long[] copy_arr(long[] arr, long[] arr1) { for (int i = 0; i < arr.length; i++) { arr1[i] = arr[i]; } return arr; } /////// For GCD public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } /// gcd of array static long gcd_arr(long arr[], long n) { long result = 0; for (long element: arr){ result = gcd(result, element); if(result == 1) { return 1; } } return result; } //////// Forprime public static boolean isPrime(long n) { if (n < 2) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sqrtN = (long) Math.sqrt(n) + 1; for (long i = 6L; i <= sqrtN; i += 6) { if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; } return true; } //////Using array as Set public static boolean[] arr_set(boolean[] arr, int n) { for (int i = 0; i < n; i++) { int x = sc.nextInt(); arr[x] = true; } return arr; } /// Fidning min in array public static long min_arr(long[] arr,int l,int r){ long min=arr[l]; for(int i=l;i<r;i++){ min=Math.min(min,arr[i]); } return min; } /// Fidning max in array public static long max_arr(long[] arr,int l,int r){ long max=arr[l]; for(int i=l;i<r;i++){ max=Math.max(max,arr[i]); } return max; } ///prefix sum public static long[] pre_sum(long[] arr){ long[] prefix_sum=new long[arr.length]; prefix_sum[0]=arr[0]; for(int i=1;i<arr.length;i++){ prefix_sum[i]=prefix_sum[i-1]+arr[i]; } return prefix_sum; } ///sorted_arr public static boolean sorted_arr(long[] arr,long[] arr_sorted){ for(int i=0;i<arr.length;i++){ if(arr[i]!=arr_sorted[i]){ return false; } } return true; } public static boolean sorted_arr_increasing(long ar[],long n){ for(long i=0;i<n-1;i++){ if(ar[(int) i]>ar[(int) (i+1)]) return false; } return true; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] readArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } public static long fact(long n) { long fact = 1; for (long i = 1; i <= n; i++) { fact *= i; } return fact; } public static long nCr(long n, long r) { long res = 1; for (long i = 0; i < r; i++) { res *= (n - i); res /= (i + 1); } return res; } public static long pCr(long n, long r) { return fact(n) / (fact(n-r)); } static boolean isSubSequence(String str1, String strm, int m, int n) { int j = 0; for (int i = 0; i < n && j < m; i++) if (str1.charAt(j) == strm.charAt(i)) j++; return (j == m); } public static boolean cmp(int a, int b) { return a > b; } static boolean palindrome(String x){ String s=""; for(int i=x.length()-1;i>=0;i--){ s+=x.charAt(i); } if(s.equals(x)){ return true; } return false; } public static class pair { long a; long b; pair(long a, long b){ this.a=a; this.b=b; } } static String toBinary(int x, int len) { if (len > 0) { return String.format("%" + len + "s", Integer.toBinaryString(x)).replaceAll(" ", "0"); } return null; } static long maxSubArraySum(long[] a) { int size = a.length; long max_so_far = Long.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } public static List<Integer> primeNumbers = new LinkedList<>(); public static void primeChecker(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } } public static void main(String[] args) throws IOException { // (fact(n)/(fact(i)*fact(n-i))) // for(Map.Entry<String,Integer> entry : tree Map.entrySet()) { // String key = entry.getKey(); // Integer value = entry.getValue(); // // } //File in = new File("input.txt"); //Writer wr= new FileWriter("output.txt"); //BigInteger n = new BigInteger(String.valueOf(sc.nextInt())); //StringBuilder sb= new StringBuilder(); //Arrays.sort(myArr, (a, b) -> a[0] - b[0]); for index at 0 long t=fs.nextLong(); while (t-->0){ long n; long a=0; long b=0; long c=0; n=fs.nextLong(); for(int i=1; i<=n; i++){ arr[i]=fs.nextLong(); } for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) ss[i][j] = ww[i][j] = 0; a = 0; for(int i=1; i<=n; i++) { b = 0; for(int j=i+1; j<=n; j++) { if(arr[j] < arr[i]) b++; ww[i][j] = (int) b; } a += b; } for(int j=1; j<=n; j++) { b = 0; for(int i=j; i>=1; i--) { b += ww[i][j]; ss[i][j] = (int) b; } } long ans = 0; for(int i=1; i<=n-3; i++) { c = ww[i][(int) n]; a -= c; for(int j=i+2; j<n; j++) { if(arr[i] < arr[j]) { b = a; c = ss[i+1][j]; b -= c; c = ww[j][(int) n]; b -= c; c = ss[j+1][(int) n]; b -= c; ans += b; } } } out.println(ans); } out.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
0c08253e24d4d9c806af327f5520d4a0
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int mod = (int)1e9+7; static boolean[] prime = new boolean[1]; static int[][] dir1 = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int[][] dir2 = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; static { for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i < prime.length; i++) { if (prime[i]) { for (int k = 2; i * k < prime.length; k++) { prime[i * k] = false; } } } } static class JoinSet { int[] fa; JoinSet(int n) { fa = new int[n]; for (int i = 0; i < n; i++) fa[i] = i; } int find(int t) { if (t != fa[t]) fa[t] = find(fa[t]); return fa[t]; } void join(int x, int y) { x = find(x); y = find(y); fa[x] = y; } } static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static int get() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Integer.parseInt(ss); } static long getx() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Long.parseLong(ss); } static int[] getint() throws Exception { String[] s = bf.readLine().split(" "); int[] a = new int[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(s[i]); } return a; } static long[] getlong() throws Exception { String[] s = bf.readLine().split(" "); long[] a = new long[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(s[i]); } return a; } static String getstr() throws Exception { return bf.readLine(); } static void println() throws Exception { bw.write("\n"); } static void print(int a) throws Exception { bw.write(a + "\n"); } static void print(long a) throws Exception { bw.write(a + "\n"); } static void print(String a) throws Exception { bw.write(a + "\n"); } static void print(int[] a) throws Exception { for (int i : a) { bw.write(i + " "); } println(); } static void print(long[] a) throws Exception { for (long i : a) { bw.write(i + " "); } println(); } static void print(int[][] a) throws Exception { for (int i[] : a) print(i); } static void print(long[][] a) throws Exception { for (long[] i : a) print(i); } static void print(char[] a) throws Exception { for (char i : a) { bw.write(i + ""); } println(); } static long pow(long a, long b) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans *= a; } a *= a; b >>= 1; } return ans; } static int powmod(long a, long b, int mod) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return (int)ans; } static void sort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void sort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void resort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } static void resort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } static int max(int a, int b) { return Math.max(a, b); } static int min(int a, int b) { return Math.min(a, b); } static long max(long a, long b) { return Math.max(a, b); } static long min(long a, long b) { return Math.min(a, b); } static int max(int[] a) { int max = a[0]; for (int i : a) max = max(max, i); return max; } static int min(int[] a) { int min = a[0]; for (int i : a) min = min(min, i); return min; } static long max(long[] a) { long max = a[0]; for (long i : a) max = max(max, i); return max; } static long min(long[] a) { long min = a[0]; for (long i : a) min = min(min, i); return min; } static int abs(int a) { return Math.abs(a); } static long abs(long a) { return Math.abs(a); } static void yes() throws Exception { print("Yes"); } static void no() throws Exception { print("No"); } static int[] getarr(List<Integer> list) { int n = list.size(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = list.get(i); return a; } public static void main(String[] args) throws Exception { int t = get(); while (t-- > 0){ int n = get(); int[] p = getint(); long ans = 0; int f[][] = new int[n][n+1]; for(int i = 1;i <= n;i++){ int c = 0; for(int j = n-1;j >= 0;j--){ f[j][i] = c; if(p[j] < i) c++; } } int[][] s = new int[n][n+1]; for(int i = 0;i < n;i++){ for(int j = 1;j <= n;j++) { s[i][j] = s[i][j-1]+f[i][p[j-1]]; } } for(int i = 0;i < n-3;i++){ for(int j = i+2;j < n-1;j++){ if(p[i] < p[j]) ans += s[j][j]-s[j][i+1]; } } print(ans); } bw.flush(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
aac22ce5c0b7417c9cd3a8065ab5e9f9
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class C { static class RealScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } public boolean isSorted(List<Long> list) { for (int i = 0; i < list.size() - 1; i++) { if (list.get(i) > list.get(i + 1)) return false; } return true; } } public static void main(String[] args) { RealScanner sc = new RealScanner(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) { long x = sc.nextLong(); list.add(x); } long res = 0; long[][] pre = new long[n + 5][n + 5]; // for (int i = 0; i <= n + 1; i++) { // for (int j = 0; j <= n + 1; j++) { // pre[i][j] = 0; // } // } for (int i = 1; i <= n; i++) { for (int j = n; j >= i; j--) { pre[i][j] += pre[i][j + 1]; if (list.get(i - 1) > list.get(j - 1)) { long val = pre[i][j]; val++; pre[i][j] = val; } } for (int j = 1; j <= n; j++) { pre[i][j] = pre[i][j] + pre[i - 1][j]; } } for (int i = 0; i < n; i++) { for (int j = i + 2; j < n; j++) { if (list.get(i) < list.get(j)) { res += (pre[j][j + 2] - pre[i + 1][j + 2]); } } } out.println(res); } out.flush(); out.close(); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9916bfd0f8ca2a1a43d26602a1fcf509
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = true; void solve(int t) { int n = sc.nextInt(); int a[] = sc.readIntArray(n); int c[] = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] < a[i]) { c[i]++; } } } long ans = 0; for (int i = 0; i < n; i++) { int cnt = 0; tree = new int[5005]; for (int j = i + 1; j < n; j++) { int big = sum(5003) - sum(a[j]); cnt += c[j]; cnt -= big; if (a[j] > a[i]) { ans += cnt - c[j]; } add(a[j]); } } System.out.println(ans); } int tree[]; void add(int i) { for (i = i + 1; i < tree.length; i += (i & -i)) tree[i]++; } int sum(int i) { int sum = 0; for (i = i + 1; i > 0; i -= (i & -i)) sum += tree[i]; return sum; } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c); obj.solve(c); obj.flush(); } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
874fabab55b6854e57d30e06ef41edab
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CTokitsukazeAndStrangeInequality solver = new CTokitsukazeAndStrangeInequality(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class CTokitsukazeAndStrangeInequality { int n; int N = 5005; int[] t = new int[N]; int[] t2 = new int[N]; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } long res = 0; for (int i = 1; i <= n - 2; i++) { for (int j = 1; j <= n; j++) { t[j] = 0; t2[j] = 0; } for (int j = i + 3; j <= n; j++) { add(a[j], 1); } add2(a[i + 1], 1); int sum = sum(a[i + 1]); for (int j = i + 2; j <= n - 1; j++) { if (a[i] < a[j]) { res += sum; } add(a[j + 1], -1); sum -= (sum2(n) - sum2(a[j + 1])); add2(a[j], 1); sum += sum(a[j]); } } out.println(res); } int lowbit(int x) { return x & -x; } void add(int x, int c) { for (int i = x; i <= n; i += lowbit(i)) { t[i] += c; } } int sum(int x) { int res = 0; for (int i = x; i > 0; i -= lowbit(i)) { res += t[i]; } return res; } void add2(int x, int c) { for (int i = x; i <= n; i += lowbit(i)) { t2[i] += c; } } int sum2(int x) { int res = 0; for (int i = x; i > 0; i -= lowbit(i)) { res += t2[i]; } return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
d9df690189f34fee3ac5e7661a431432
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = sc.nextInt(); while( t-- > 0) { int n = sc.nextInt(); int mat[][] = new int[n][n]; int arr[] = new int[n]; for( int i = 0; i < n ;i++) { arr[i] = sc.nextInt(); } long ans = 0; for( int i = 0 ; i< n ;i++) { int temp = 0; for( int j = n-1 ; j>=0 ;j--){ mat[i][j] = temp; if( arr[j] < arr[i]) { temp++; } } } for( int i = 0 ;i< n; i++) { long temp = 0; for( int j = i-1 ;j >= 0; j--) { if( arr[j] < arr[i]) { ans+=temp; } temp+=mat[j][i]; } } out.println(ans); } out.flush(); } static class pair{ char c; int val; pair( char c , int val){ this.c = c; this.val = val; } } /* * time for a change */ public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static ArrayList<Long> allfactors(long abs) { HashMap<Long,Integer> hm = new HashMap<>(); ArrayList<Long> rtrn = new ArrayList<>(); for( long i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( long x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9ef77538369b9f20027b879414665205
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; final static long INF = Long.MAX_VALUE; final static long NEG_INF = Long.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(); int[] arr = readIntArray(n); FT ft1 = new FT(n + 1); ft1.update(arr[0], 1); long ans = 0L; for (int b = 1; b < n - 2; b++) { FT ft2 = new FT(n + 1); for (int i = b + 1; i < n; i++) ft2.update(arr[i], 1); for (int c = b + 1; c < n - 1; c++) { ft2.update(arr[c], -1); ans += ft1.query(0, arr[c]) * ft2.query(0, arr[b]); } ft1.update(arr[b], 1); } out.println(ans); } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // ==================== CUSTOM CLASSES ================================ static class Pair { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } private static void yes() { out.println("YES"); } private static void no() { out.println("NO"); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { int[] tree; int n; FT(int n) { this.n = n; this.tree = new int[n + 1]; // for (int i = 1; i <= n; i++) { // update(i, arr[i - 1]); // } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
3be07a11971ccb071e2952441b729e19
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.Arrays; import java.util.*; import java.util.Scanner; import java.util.StringTokenizer; public class copy { static int log=18; static int[][] ancestor; static int[] depth; static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i]) { arr.add(i); } } } public static long fac(long N, long mod) { if (N == 0) return 1; if(N==1) return 1; return ((N % mod) * (fac(N - 1, mod) % mod)) % mod; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(long n, long r, long p) { if (n < r) return 0; // Base case if (r == 0) return 1; return ((fac(n, p) % p * (modInverse(fac(r, p), p) % p)) % p * (modInverse(fac(n - r, p), p) % p)) % p; } public static int find(int[] parent, int x) { if (parent[x] == x) return x; return find(parent, parent[x]); } public static void merge(int[] parent, int[] rank, int x, int y,int[] child) { int x1 = find(parent, x); int y1 = find(parent, y); if (rank[x1] > rank[y1]) { parent[y1] = x1; child[x1]+=child[y1]; } else if (rank[y1] > rank[x1]) { parent[x1] = y1; child[y1]+=child[x1]; } else { parent[y1] = x1; child[x1]+=child[y1]; rank[x1]++; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long[][] ncr(int n,int r) { long[][] dp=new long[n+1][r+1]; for(int i=0;i<=n;i++) dp[i][0]=1; for(int i=1;i<=n;i++) { for(int j=1;j<=r;j++) { if(j>i) continue; dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; } } return dp; } public static boolean prime(long N) { int c=0; for(int i=2;i*i<=N;i++) { if(N%i==0) ++c; } return c==0; } public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child) { int c=0; for(int i:arr.get(x)) { if(i!=parent) { // System.out.println(i+" hello "+x); depth[i]=depth[x]+1; ancestor[i][0]=x; // if(i==2) // System.out.println(parent+" hello"); for(int j=1;j<log;j++) ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1]; c+=sparse_ancestor_table(arr,i,x,child); } } child[x]=1+c; return child[x]; } public static int lca(int x,int y) { if(depth[x]<depth[y]) { int temp=x; x=y; y=temp; } x=get_kth_ancestor(depth[x]-depth[y],x); if(x==y) return x; // System.out.println(x+" "+y); for(int i=log-1;i>=0;i--) { if(ancestor[x][i]!=ancestor[y][i]) { x=ancestor[x][i]; y=ancestor[y][i]; } } return ancestor[x][0]; } public static int get_kth_ancestor(int K,int x) { if(K==0) return x; int node=x; for(int i=0;i<log;i++) { if(K%2!=0) { node=ancestor[node][i]; } K/=2; } return node; } public static ArrayList<Integer> primeFactors(int n) { // Print the number of 2s that divide n ArrayList<Integer> factors=new ArrayList<>(); if(n%2==0) factors.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if(n%i==0) factors.add(i); while (n%i == 0) { n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { factors.add(n); } return factors; } static long ans=1,mod=1000000007; public static void recur(long X,long N,int index,ArrayList<Integer> temp) { // System.out.println(X); if(index==temp.size()) { System.out.println(X); ans=((ans%mod)*(X%mod))%mod; return; } for(int i=0;i<=60;i++) { if(X*Math.pow(temp.get(index),i)<=N) recur(X*(long)Math.pow(temp.get(index),i),N,index+1,temp); else break; } } public static int upper(ArrayList<Integer> temp,int X) { int l=0,r=temp.size()-1; while(l<=r) { int mid=(l+r)/2; if(temp.get(mid)==X) return mid; // System.out.println(mid+" "+temp.get(mid)); if(temp.get(mid)<X) l=mid+1; else { if(mid-1>=0 && temp.get(mid-1)>=X) r=mid-1; else return mid; } } return -1; } public static int lower(ArrayList<Integer> temp,int X) { int l=0,r=temp.size()-1; while(l<=r) { int mid=(l+r)/2; if(temp.get(mid)==X) return mid; // System.out.println(mid+" "+temp.get(mid)); if(temp.get(mid)>X) r=mid-1; else { if(mid+1<temp.size() && temp.get(mid+1)<=X) l=mid+1; else return mid; } } return -1; } public static int[] check(String shelf,int[][] queries) { int[] arr=new int[queries.length]; ArrayList<Integer> indices=new ArrayList<>(); for(int i=0;i<shelf.length();i++) { char ch=shelf.charAt(i); if(ch=='|') indices.add(i); } for(int i=0;i<queries.length;i++) { int x=queries[i][0]-1; int y=queries[i][1]-1; int left=upper(indices,x); int right=lower(indices,y); if(left<=right && left!=-1 && right!=-1) { arr[i]=indices.get(right)-indices.get(left)+1-(right-left+1); } else arr[i]=0; } return arr; } static boolean check; public static void check(ArrayList<ArrayList<Integer>> arr,int x,int[] color,boolean[] visited) { visited[x]=true; PriorityQueue<Integer> pq=new PriorityQueue<>(); for(int i:arr.get(x)) { if(color[i]<color[x]) pq.add(color[i]); if(color[i]==color[x]) check=false; if(!visited[i]) check(arr,i,color,visited); } int start=1; while(pq.size()>0) { int temp=pq.poll(); if(temp==start) ++start; else break; } if(start!=color[x]) check=false; } static boolean cycle; public static void cycle(boolean[] stack,boolean[] visited,int x,ArrayList<ArrayList<Integer>> arr) { if(stack[x]) { cycle=true; return; } visited[x]=true; for(int i:arr.get(x)) { if(!visited[x]) { cycle(stack,visited,i,arr); } } stack[x]=false; } public static int check(char[][] ch,int x,int y) { int cnt=0; int c=0; int N=ch.length; int x1=x,y1=y; while(c<ch.length) { if(ch[x][y]=='1') ++cnt; // if(x1==0 && y1==3) // System.out.println(x+" "+y+" "+cnt); x=(x+1)%N; y=(y+1)%N; ++c; } return cnt; } public static void s(char[][] arr,int x) { char start=arr[arr.length-1][x]; for(int i=arr.length-1;i>0;i--) { arr[i][x]=arr[i-1][x]; } arr[0][x]=start; } public static void shuffle(char[][] arr,int x,int down) { int N= arr.length; down%=N; char[] store=new char[N-down]; for(int i=0;i<N-down;i++) store[i]=arr[i][x]; for(int i=0;i<arr.length;i++) { if(i<down) { // Printing rightmost // kth elements arr[i][x]=arr[N + i - down][x]; } else { // Prints array after // 'k' elements arr[i][x]=store[i-down]; } } } public static String form(int C1,char ch1,char ch2) { char ch=ch1; String s=""; for(int i=1;i<=C1;i++) { s+=ch; if(ch==ch1) ch=ch2; else ch=ch1; } return s; } public static void printArray(long[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public static boolean check(long mid,long[] arr,long K) { long[] arr1=Arrays.copyOfRange(arr,0,arr.length); long ans=0; for(int i=0;i<arr1.length-1;i++) { if(arr1[i]+arr1[i+1]>=mid) { long check=(arr1[i]+arr1[i+1])/mid; // if(mid==5) // System.out.println(check); long left=check*mid; left-=arr1[i]; if(left>=0) arr1[i+1]-=left; ans+=check; } // if(mid==5) // printArray(arr1); } // if(mid==5) // System.out.println(ans); ans+=arr1[arr1.length-1]/mid; return ans>=K; } public static long search(long sum,long[] arr,long K) { long l=1,r=sum/K; while(l<=r) { long mid=(l+r)/2; if(check(mid,arr,K)) { if(mid+1<=sum/K && check(mid+1,arr,K)) l=mid+1; else return mid; } else r=mid-1; } return -1; } public static void primeFactors(int n,HashSet<Integer> hp) { // Print the number of 2s that divide n ArrayList<Integer> factors=new ArrayList<>(); if(n%2==0) hp.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if(n%i==0) hp.add(i); while (n%i == 0) { n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { hp.add(n); } } public static boolean check(String s) { HashSet<Character> hp=new HashSet<>(); char ch=s.charAt(0); for(int i=1;i<s.length();i++) { // System.out.println(hp+" "+s.charAt(i)); if(hp.contains(s.charAt(i))) { // System.out.println(i); // System.out.println(hp); // System.out.println(s.charAt(i)); return false; } if(s.charAt(i)!=ch) { hp.add(ch); ch=s.charAt(i); } } return true; } public static int check_end(String[] arr,boolean[] st,char ch) { for(int i=0;i<arr.length;i++) { if(ch==arr[i].charAt(0) && !st[i] && ch==arr[i].charAt(arr[i].length()-1)) return i; } for(int i=0;i<arr.length;i++) { if(ch==arr[i].charAt(0) && !st[i]) return i; } return -1; } public static int check_start(String[] arr,boolean[] st,char ch) { for(int i=0;i<arr.length;i++) { // if(ch=='B') // { // if(!st[i]) // System.out.println(arr[i]+" hello"); // } if(ch==arr[i].charAt(arr[i].length()-1) && !st[i] && ch==arr[i].charAt(0)) return i; } for(int i=0;i<arr.length;i++) { // if(ch=='B') // { // if(!st[i]) // System.out.println(arr[i]+" hello"); // } if(ch==arr[i].charAt(arr[i].length()-1) && !st[i]) return i; } return -1; } public static boolean palin(int N) { String s=""; while(N>0) { s+=N%10; N/=10; } int l=0,r=s.length()-1; while(l<=r) { if(s.charAt(l)!=s.charAt(r)) return false; ++l; --r; } return true; } public static boolean check(long org_s,long org_d,long org_n,long check_ele) { if(check_ele<org_s) return false; if((check_ele-org_s)%org_d!=0) return false; long num=(check_ele-org_s)/org_d; // if(check_ele==5) // System.out.println(num+" "+org_n); return num+1<=org_n; } public static long check(long c,long c_diff,long mod,long b_start,long c_start, long c_end,long b_end,long b_diff) { // System.out.println(c); long max=Math.max(c,b_diff); long min=Math.min(c,b_diff); long lcm=(max/gcd(max,min))*min; // System.out.println(lcm); // System.out.println(c); // System.out.println(c_diff); // if(b_diff>c) // { long start_point=c_diff/c-c_diff/lcm; // System.out.println(start_point); // } // else // { // start_point=c_diff/b_diff-c_diff/c; // } // System.out.println(c+" "+start_point); return (start_point%mod*start_point%mod)%mod; } public static boolean check_bounds(int x,int y,int[][] arr,int N,int M) { return x>=0 && x<N && y>=0 && y<M && (arr[x][y]==1 || arr[x][y]==9); } static boolean found=false; public static void check(int x,int y,int[][] arr,boolean status[][]) { if(arr[x][y]==9) { found=true; return; } status[x][y]=true; if(check_bounds(x-1,y,arr,arr.length,arr[0].length)&& !status[x-1][y]) check(x-1,y,arr,status); if(check_bounds(x+1,y,arr,arr.length,arr[0].length)&& !status[x+1][y]) check(x+1,y,arr,status); if(check_bounds(x,y-1,arr,arr.length,arr[0].length)&& !status[x][y-1]) check(x,y-1,arr,status); if(check_bounds(x,y+1,arr,arr.length,arr[0].length)&& !status[x][y+1]) check(x,y+1,arr,status); } public static int check(int[] s,int[] s2) { int cnt=0; for(int i=0;i<s.length;i++) { if(s[i]!=s2[i]) ++cnt; } return cnt; } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int T=Reader.nextInt(); A:for(int m=1;m<=T;m++) { int N=Reader.nextInt(); int[] arr=new int[N]; for(int i=0;i<N;i++) arr[i]=Reader.nextInt(); int[][] great=new int[N][N]; for(int i=0;i<N;i++) { int cnt=0; for(int j=N-1;j>i;j--) { if(arr[i]>arr[j]) ++cnt; great[i][j]=cnt; } } // for(int i=0;i<N;i++) // { // for(int j=0;j<N;j++) // output.write(great[i][j]+" "); // output.write("\n"); // } for(int i=0;i<N;i++) { for(int j=1;j<N;j++) { great[j][i]+=great[j-1][i]; } } // for(int i=0;i<N;i++) // { // for(int j=0;j<N;j++) // output.write(great[i][j]+" "); // output.write("\n"); // } long ans=0; for(int i=0;i<N;i++) { for(int j=i+2;j<N-1;j++) { if(arr[j]>arr[i]) { ans+=great[j-1][j+1]-great[i][j+1]; } } } output.write(ans+"\n"); } output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class TreeNode { int data; TreeNode left; TreeNode right; TreeNode(int data) { left=null; right=null; this.data=data; } } class div { int x; int y; div(int x,int y) { this.x=x; this.y=y; } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
9bbe059aca44fff8f456e2f27be1619e
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { static IOHandler sc = new IOHandler(); public static void main(String[] args) { // TODO Auto-generated method stub int testCases = sc.nextInt(); for (int i = 1; i <= testCases; ++i) { solve(i); } } private static void solve(int t) { int n = sc.nextInt(); int [] arr = new int [n]; for (int i = 0; i < n; ++i) arr[i] = sc.nextInt(); int [] bit = new int [n + 1]; long total = 0; long val; long greater; for (int c = arr.length - 2; c >= 2; --c) { addToBitL(bit, arr[c + 1]); greater = 0; for (int i = c - 1; i >= 1; --i) { greater += getNumSmaller(bit, arr[i]); if (arr[i - 1] < arr[c]) { total += greater; } } } System.out.println(total); } private static void addToBitL(int [] bit, int num) { for (int i = num; i < bit.length; i += (i & -i) ) { ++bit[i]; } } private static int getNumSmaller (int [] bit, int num) { int result = 0; for (int i = num; i > 0; i -= (i & -i)) { result += bit[i]; } return result; } private static void addToBitG(int [] bit, int num) { for (int i = num; i > 0; i -= (i & -i)) { bit[i]++; } } private static int getNumGreater(int [] bit, int num) { int result = 0; for (int i = num; i < bit.length; i += (i & -i) ) { result += bit[i]; } return result; } private static class IOHandler { BufferedReader br; StringTokenizer st; public IOHandler() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
d761a4c8efabd18e9d55765e8e97b047
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.math.BigInteger; import static java.lang.Math.*; import static java.lang.System.*; import java.util.*; public class Main { static public void main(String[] args){ Read in = new Read(System.in); int t =in.nextInt(); while(t>0){ t--; solve(in); } } static void solve(Read in){ int n = in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=in.nextInt(); } long[][] minc = new long[n+1][n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ minc[i][j] = minc[i-1][j]; if(a[i-1]<j){ minc[i][j]++; } } } long ans = 0; for(int i=1;i<n-2;i++){ for(int j=i+1;j<n-1;j++){ ans+=minc[i][a[j]]*(a[i]-1 - minc[j+1][a[i]]); } } out.println(ans); } void shuffleArray(long[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static class Read {//自定义快读 Read public BufferedReader reader; public StringTokenizer tokenizer; public Read(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { String str = null; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long gcd(long a, long b) { return (a % b == 0) ? b : gcd(b, a % b); } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output
PASSED
e7cae5c04dc111f17548501f4d9c2223
train_108.jsonl
1652020500
Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a &lt; b &lt; c &lt; d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a &lt; p_c$$$ and $$$p_b &gt; p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main (String[] args) throws java.lang.Exception { Reader sc = new Reader(); StringBuffer str = new StringBuffer(""); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int arr[] = new int[n]; for(int i = 0 ; i < n ; i++) { arr[i] = sc.nextInt(); } long ans = 0; int cnt[] = new int[n+1]; for(int i = 0 ; i < n ; i++) { cnt[arr[i]]++; } for(int i = 1 ; i <= n ; i++) { cnt[i] += cnt[i-1]; } for(int i = 0 ; i < n ; i++) { for(int j = arr[i] ; j <= n ; j++) { cnt[j]--; } long tot = 0; for(int j = i-1 ; j >= 0 ; j--) { if(arr[j] < arr[i]) { ans += tot; } tot += cnt[arr[j]-1]; } } System.out.println(ans); } } }
Java
["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"]
1.5 seconds
["3\n0\n28"]
NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 &lt; p_3$$$ and $$$p_2 &gt; p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$.
Java 11
standard input
[ "brute force", "data structures" ]
d6a123dab1263b0e7b297ca2584fe701
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
1,600
For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.
standard output