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
8d15c9ab380d31585ce0c336517a0081
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class VentureFD { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int q = sc.nextInt(); PrintWriter out = new PrintWriter(System.out); int N = (int) Math.pow(2, Math.ceil(Math.log(n)/Math.log(2))); //padding long[] in = new long[N+1]; long[] in2 = new long[N+1]; SegmentTree st = new SegmentTree(in); SegmentTree st2 = new SegmentTree(in2); for(int i=0; i<q; i++){ int t = sc.nextInt(); if(t == 1) { int d = sc.nextInt(); int o = sc.nextInt(); // in[d[p]] = Math.min(o[p],a); // in2[d[p]] = Math.min(o[p],b); int pa = (int)st.query(d, d); int pb = (int)st2.query(d, d); int pa2 = Math.min(a, pa + o); int pb2 = Math.min(b, pb + o); st.update_point(d, -pa + pa2); st2.update_point(d, -pb + pb2); } else { int period = sc.nextInt(); long after = st.query(period + k, n); long before = st2.query(1, period-1); // System.out.println(after+" "+before); // int res = st.query(per[p2]+k+1, N) + st2.query(0, per[p2]-1); out.println(after+before); } } out.flush(); out.close(); // for(int i=1; i<n; i++){ // preCalcD[i] += preCalcD[i-1]; // preCalcA[i] += preCalcA[i-1]; // } // System.out.println(Arrays.toString(preCalcD)); // System.out.println(Arrays.toString(preCalcA)); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(FileReader f) { br = new BufferedReader(f); } public boolean ready() throws IOException { return br.ready(); } Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a multipls of 2 (i.e. after padding) long[] array, sTree, lazy; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new long[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { build(node<<1,b,(b+e)/2); build((node<<1)+1,(b+e)/2+1,e); sTree[node] = sTree[node<<1]+sTree[(node<<1)+1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[(index<<1) + 1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] += (e-b+1)*val; lazy[node] += val; } else { propagate(node, b, e); update_range(node<<1,b,(b+e)/2,i,j,val); update_range((node<<1)+1,(b+e)/2+1,e,i,j,val); sTree[node] = sTree[node<<1] + sTree[(node<<1)+1]; } } void propagate(int node, int b, int e) { int mid = (b+e)/2; lazy[node<<1] += lazy[node]; lazy[(node<<1)+1] += lazy[node]; sTree[node<<1] += (mid-b+1)*lazy[node]; sTree[(node<<1)+1] += (e-mid)*lazy[node]; lazy[node] = 0; } long query(int i, int j) { return query(1,1,N,i,j); } long query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return 0; if(b>= i && e <= j) return sTree[node]; propagate(node, b, e); return query(node<<1,b,(b+e)/2,i,j) + query((node<<1)+1,(b+e)/2+1,e,i,j); } } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
826e491970d7e9eae64204f511cbaaa2
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
import java.io.*; import java.util.*; /** * * @author Sourav Kumar Paul (spaul100) * NIT Silchar */ public class SolveD { public static Reader in; public static PrintWriter out; public static long mod = 1000000007; public static long inf = 100000000000000000l; public static long fac[],inv[]; public static int union[]; public static void solve(){ int n = in.nextInt(); int k = in.nextInt(); long a = in.nextLong(); long b = in.nextLong(); int q = in.nextInt(); long arr1[] = new long[n]; long arr2[] = new long[n]; int x = (int) Math.pow(2, Math.ceil(Math.log(n) / Math.log(2))); size = 2 * x - 1; left = new long[2 * x - 1]; right = new long[2 * x - 1]; sizeArray = n; constructTree(arr1,left); constructTree(arr2,right); while(q-->0) { int type = in.nextInt(); if(type == 1) { int xx = in.nextInt()-1; long z = in.nextLong(); long nn = Math.min(arr1[xx] + z, b); long ss = Math.max(0, nn-arr1[xx]); updateSegmentTree(arr1, left, xx,ss); nn = Math.min(arr2[xx] + z, a); ss = Math.max(0, nn-arr2[xx]); updateSegmentTree(arr2, right, xx,ss); } else { int start = in.nextInt()-1; long ans = 0; if(start >0) ans = querySum(arr1,left,0,start-1); if(start+k <n) ans += querySum(arr2, right, start+k, n-1); out.println(ans); } } // out.println(Arrays.toString(arr2)); } /** * ############################### Template ################################ */ private static long left[],right[]; private static int size, sizeArray; public static void constructTree(long input[], long segTree[]) { constructTree(input, segTree, 0, sizeArray - 1, 0); } private static void constructTree(long input[], long segTree[], int low, int high, int pos) { if (low == high) { segTree[pos] = input[low]; return; } int mid = (low + high) / 2; constructTree(input, segTree, low, mid, 2 * pos + 1); constructTree(input, segTree, mid + 1, high, 2 * pos + 2); segTree[pos] = segTree[2 * pos + 1] + segTree[2 * pos + 2]; } public static void updateSegmentTree(long input[], long segTree[], int index, long delta) { input[index] += delta; updateSegmentTree(input, segTree,index, 0, input.length - 1, delta, 0); } private static void updateSegmentTree(long input[], long segTree[], int index, int low, int high, long delta, int pos) { if (index < low || index > high) { return; } if (low == high) { segTree[pos] += delta; return; } int mid = (low + high) / 2; updateSegmentTree(input, segTree,index, low, mid, delta, 2 * pos + 1); updateSegmentTree(input, segTree,index, mid + 1, high, delta, 2 * pos + 2); segTree[pos] = segTree[2 * pos + 1] + segTree[2 * pos + 2]; } public static long querySum(long input[], long segTree[], int qlow, int qhigh) { return querySum(input,segTree, qlow, qhigh, 0, sizeArray - 1, 0); } private static long querySum(long input[], long segTree[], int qlow, int qhigh, int low, int high, int pos) { if(low > high) return 0; if (qlow <= low && qhigh >= high) { return segTree[pos]; } if (qlow > high || qhigh < low) { return 0; } int mid = (low + high) / 2; return querySum(input, segTree,qlow, qhigh, low, mid, 2 * pos + 1) + querySum(input, segTree,qlow, qhigh, mid + 1, high, 2 * pos + 2); } public static class Pair implements Comparable{ int x,y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Object o) { Pair pp = (Pair)o; if(pp.x == x) return 0; else if (x>pp.x) return 1; else return -1; } } public static void init() { for(int i=0; i<union.length; i++) union[i] = i; } public static int find(int n) { return (union[n]==n)?n:(union[n]=find(union[n])); } public static void unionSet(int i ,int j) { union[find(i)]=find(j); } public static boolean connected(int i,int j) { return union[i]==union[j]; } public static long gcd(long a, long b) { long x = Math.min(a,b); long y = Math.max(a,b); while(x!=0) { long temp = x; x = y%x; y = temp; } return y; } public static long modPow(long base, long exp, long mod) { base = base % mod; long result =1; while(exp > 0) { if(exp % 2== 1) { result = (result * base) % mod; exp --; } else { base = (base * base) % mod; exp = exp >> 1; } } return result; } public static void cal() { fac = new long[1000005]; inv = new long[1000005]; fac[0]=1; inv[0]=1; for(int i=1; i<=1000000; i++) { fac[i]=(fac[i-1]*i)%mod; inv[i]=(inv[i-1]*modPow(i,mod-2,mod))%mod; } } public static long ncr(int n, int r) { return (((fac[n]*inv[r])%mod)*inv[n-r])%mod; } SolveD() throws IOException { in = new Reader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); out.close(); } public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try { new SolveD(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } public static class Reader { public BufferedReader reader; public StringTokenizer st; public Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() throws IOException{ return reader.readLine(); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
a6001d7e78586ba663f652e89783b411
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), k = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt(), q = sc.nextInt(); FenwickTree fa = new FenwickTree(n), fb = new FenwickTree(n); for(int i = 1; i <= n; ++i) { fa.update(i, a); fb.update(i, b); } while(q-->0) if(sc.nextInt() == 1) { int day = sc.nextInt(), orders = sc.nextInt(); fa.decrement(day, orders); fb.decrement(day, orders); } else { int l = sc.nextInt(), r = l + k - 1; int ans = 0; if(l > 1) ans += b * (l - 1) - fb.query(1, l - 1); if(r < n) ans += a * (n - r) - fa.query(r + 1, n); out.println(ans); } out.flush(); out.close(); } static class FenwickTree { int[] ft; FenwickTree(int n) { ft = new int[n + 1]; } void decrement(int k, int d) { int val = query(k, k); update(k, -Math.min(d, val)); } void update(int k, int val) { while(k < ft.length) { ft[k] += val; k += k & -k; } } int query(int k) { int sum = 0; while(k > 0) { sum += ft[k]; k ^= k & -k; } return sum; } int query(int l, int r) { return query(r) - query(l - 1); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
20f93ff219ecbad020d7247094b68f2d
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class FactoryRepairs { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int K = sc.nextInt(); int A = sc.nextInt(); int B = sc.nextInt(); int Q = sc.nextInt(); StringBuilder sb = new StringBuilder(); SegmentTree pre = new SegmentTree(N + 1); SegmentTree post = new SegmentTree(N + 1); for (int q = 0; q < Q; q++) { int T = sc.nextInt(); if (T == 1) { int D = sc.nextInt(); int V = sc.nextInt(); long preAmt = Math.min(B, pre.get(D) + V); pre.insert(D, preAmt); long postAmt = Math.min(A, post.get(D) + V); post.insert(D, postAmt); } else { int P = sc.nextInt(); long preSum = pre.get(1, P - 1); long postSum = post.get(P + K, N); long total = preSum + postSum; sb.append(total + "\n"); } } System.out.print(sb.toString()); } /** * Here is a Segment Tree implementation. It currently does sums of longs. * See the comments to find where to change the data-type and function of this Segment Tree. */ public static class SegmentTree { public SegmentTreeNode[] leaves; public SegmentTreeNode root; public SegmentTree(int n) { this.leaves = new SegmentTreeNode[n]; this.root = new SegmentTreeNode(this, null, 0, n - 1); } // modify the data-type of this segment tree public SegmentTree(long[] vals) { this(vals.length); for (int i = 0; i < vals.length; i++) { this.insert(i, vals[i]); } } // modify the data-type of this segment tree public void insert(int idx, long v) { this.leaves[idx].setAndUpdate(v); } // modify the data-type of this segment tree public long get(int idx) { return this.leaves[idx].val; } // modify the data-type of this segment tree public long get(int lower, int upper) { return this.root.getRange(lower, upper); } private static class SegmentTreeNode { public int L; public int R; // modify the data-type of this segment tree public long val; public SegmentTree tree; public SegmentTreeNode parent; public SegmentTreeNode left; public SegmentTreeNode rite; public SegmentTreeNode(SegmentTree t, SegmentTreeNode p, int lower, int upper) { this.tree = t; this.parent = p; this.L = lower; this.R = upper; if (lower == upper) { this.tree.leaves[lower] = this; } else { int mid = (lower + upper) / 2; this.left = new SegmentTreeNode(tree, this, lower, mid); this.rite = new SegmentTreeNode(tree, this, mid + 1, upper); } } // modify the data-type of this segment tree public void setAndUpdate(long v) { this.val = v; this.update(); } // modify the function (i.e. max, min, sum, etc.) in this method public void update() { if (this.left != null && this.rite != null) { this.val = this.left.val + this.rite.val; } else if (this.left != null) { this.val = this.left.val; } else if (this.rite != null) { this.val = this.rite.val; } if (this.parent != null) { this.parent.update(); } } // modify the function & the default return value in this method public long getRange(int lower, int upper) { if (this.L >= lower && this.R <= upper) { return this.val; } else if (this.L > upper || this.R < lower) { // modify the default value here (if it's not found) return 0; } else { // modify the function that this Segment Tree uses return this.left.getRange(lower, upper) + this.rite.getRange(lower, upper); } } } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 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 int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
11a648cab6858a01b903d205e584d4ec
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
import java.io.*; 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { int fa[],fb[]; void upda(int id,int val,int max){ while(id<=max){ fa[id]+=val;id+=id&-id; } } void updb(int id,int val,int max){ while(id<=max){ fb[id]+=val;id+=id&-id; } } int geta(int id){ int ans=0; while(id>0){ ans+=fa[id];id-=id&-id; }return ans; } int getb(int id){ int ans=0; while(id>0){ ans+=fb[id];id-=id&-id; }return ans; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(),k=in.nextInt(),a=in.nextInt(),b=in.nextInt(),q=in.nextInt(); int A[]=new int[n+1],B[]=new int[n+1];fa=new int[n+1];fb=new int[n+1]; while(q-->0){ int t=in.nextInt(); if(t==1){ int d=in.nextInt(),c=in.nextInt(); upda(d,Math.min(A[d]+c,a)-A[d],n);A[d]=Math.min(A[d]+c,a); updb(d,Math.min(B[d]+c,b)-B[d],n);B[d]=Math.min(B[d]+c,b); }else{ int p=in.nextInt(); out.println(getb(p-1)+geta(n)-geta(p+k-1)); } } } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
620f8a788a42dc41d6b43810b88029f5
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
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 { public static void main (String[] args) throws IOException { // your code goes here BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str=br.readLine(); Stack <Character> st=new Stack(); st.push(str.charAt(0)); for(int i=1;i<str.length();i++) { if(st.isEmpty()==false){ if(str.charAt(i)==st.peek()) st.pop(); else st.push(str.charAt(i)); } else st.push(str.charAt(i)); } if(st.isEmpty()) System.out.println("Yes"); else System.out.println("No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
52b53a518482802ef3af8080ffb2e4a8
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.text.*; /* * @IO : BufferedReader, InputStreamReader, IOException. * @Util : Scanner, Arrays, ArrayList, StringTokenizer, TreeSet. * @Util : Collections, HashMap, HashSet. * @Lang : StringBuilder, StringBuffer. * @Math : BigInteger, BigDecimal. * @Text : DecimalFormat. * @System : System.currentTimeMillis(); , System.nanoTime(); */ public class Main{ public static PrintWriter out; public static void main(String[] args){ Reader read = new Reader(); out = new PrintWriter(new BufferedOutputStream(System.out)); //---------------------Solution Start---------------------// Stack<Character> st = new Stack<>(); char[] s = read.nextLine().toCharArray(); for (int i = 0 ; i < s.length ; i++){ if (st.isEmpty() || (st.peek() != s[i])) st.push(s[i]); else st.pop(); } out.println(st.isEmpty() ? "Yes" : "No"); //---------------------Solution End---------------------// out.flush(); out.close(); } } class Reader{ BufferedReader bufferedReader; StringTokenizer stringTokenizer; public Reader(){ bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String next(){ while (stringTokenizer == null || !stringTokenizer.hasMoreElements()){ try{ stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException Ex){ Ex.printStackTrace(); } } return stringTokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(this.next()); } public long nextLong(){ return Long.parseLong(this.next()); } public double nextDouble(){ return Double.parseDouble(this.next()); } public String nextLine(){ String str = ""; try{ str = bufferedReader.readLine(); } catch (IOException Ex){ Ex.printStackTrace(); } return str; } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
2f20a0b76b5185dffcc29d9472fe5815
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.text.*; /* * @IO : BufferedReader, InputStreamReader, IOException. * @Util : Scanner, Arrays, ArrayList, StringTokenizer, TreeSet. * @Util : Collections, HashMap, HashSet. * @Lang : StringBuilder, StringBuffer. * @Math : BigInteger, BigDecimal. * @Text : DecimalFormat. * @System : System.currentTimeMillis(); , System.nanoTime(); */ public class Main{ public static PrintWriter out; public static void main(String[] args){ Reader read = new Reader(); out = new PrintWriter(new BufferedOutputStream(System.out)); //---------------------Solution Start---------------------// Stack<Character> st = new Stack<>(); char[] s = read.nextLine().toCharArray(); for (int i = 0 ; i < s.length ; i++){ if (st.isEmpty()){ st.push(s[i]); continue; } else if (!st.isEmpty() && st.peek() == '+'){ if (s[i] == '+') st.pop(); else st.push(s[i]); } else if (!st.isEmpty() && st.peek() == '-'){ if (s[i] == '-') st.pop(); else st.push(s[i]); } } out.println(st.isEmpty() ? "Yes" : "No"); //---------------------Solution End---------------------// out.close(); } } class Reader{ BufferedReader bufferedReader; StringTokenizer stringTokenizer; public Reader(){ bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String next(){ while (stringTokenizer == null || !stringTokenizer.hasMoreElements()){ try{ stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException Ex){ Ex.printStackTrace(); } } return stringTokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(this.next()); } public long nextLong(){ return Long.parseLong(this.next()); } public double nextDouble(){ return Double.parseDouble(this.next()); } public String nextLine(){ String str = ""; try{ str = bufferedReader.readLine(); } catch (IOException Ex){ Ex.printStackTrace(); } return str; } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
2241adee1dd0a26f0d206f0e5b4466c1
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.text.*; /* * @IO : BufferedReader, InputStreamReader, IOException. * @Util : Scanner, Arrays, ArrayList, StringTokenizer, TreeSet. * @Util : Collections, HashMap, HashSet. * @Lang : StringBuilder, StringBuffer. * @Math : BigInteger, BigDecimal. * @Text : DecimalFormat. * @System : System.currentTimeMillis(); , System.nanoTime(); */ //h public class Main{ public static PrintWriter out; public static void main(String[] args){ Reader read = new Reader(); out = new PrintWriter(new BufferedOutputStream(System.out)); //---------------------Solution Start---------------------// Stack<Character> st = new Stack<>(); char[] s = read.nextLine().toCharArray(); for (int i = 0 ; i < s.length ; i++){ if (st.isEmpty() || (st.peek() != s[i])) st.push(s[i]); else st.pop(); } out.println(st.isEmpty() ? "Yes" : "No"); //---------------------Solution End---------------------// out.flush(); out.close(); } } class Reader{ BufferedReader bufferedReader; StringTokenizer stringTokenizer; public Reader(){ bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String next(){ while (stringTokenizer == null || !stringTokenizer.hasMoreElements()){ try{ stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException Ex){ Ex.printStackTrace(); } } return stringTokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(this.next()); } public long nextLong(){ return Long.parseLong(this.next()); } public double nextDouble(){ return Double.parseDouble(this.next()); } public String nextLine(){ String str = ""; try{ str = bufferedReader.readLine(); } catch (IOException Ex){ Ex.printStackTrace(); } return str; } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
0a79fef2ee45c80e7c64d5c1579b22c4
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import java.io.IOException; import java.util.StringTokenizer; public class current {public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf =new BufferedReader(new InputStreamReader(System.in)); String s=bf.readLine(); int i=0; Stack<Character> stack= new Stack<Character>(); while(i!=s.length()) { if(!(stack.isEmpty())&&s.charAt(i)==stack.peek() ) { stack.pop(); } else {stack.push(s.charAt(i)); } i++; } if(stack.isEmpty()) {System.out.println("Yes");} else {System.out.println("No");} } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
8c1d2111a656a6623cfd9299641c5d04
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import java.io.IOException; import java.util.StringTokenizer; public class current {public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bz =new BufferedReader(new InputStreamReader(System.in)); String s=bz.readLine(); int i=0; Stack<Character> stack= new Stack<Character>(); while(i!=s.length()) { if(!(stack.isEmpty())&&s.charAt(i)==stack.peek() ) { stack.pop(); } else {stack.push(s.charAt(i)); } i++; } if(stack.isEmpty()) {System.out.println("Yes");} else {System.out.println("No");} } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
1ccdafc5c9528c63d801b4246d631b34
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; import java.io.IOException; import java.util.StringTokenizer; public class current {public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf =new BufferedReader(new InputStreamReader(System.in)); String s=bf.readLine(); int i=0; Stack<Character> stack= new Stack<Character>(); while(i!=s.length()) { if(!(stack.isEmpty())&&s.charAt(i)==stack.peek() ) { stack.pop(); } else {stack.push(s.charAt(i)); } i++; } if(stack.isEmpty()) {System.out.println("Yes");} else {System.out.println("No");} } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
debc8b0147d2c88dad35d8a010bc1d9e
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; import java.io.IOException; import java.util.StringTokenizer; public class current {public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bz =new BufferedReader(new InputStreamReader(System.in)); String s=bz.readLine(); int i=0; Stack<Character> stack= new Stack<Character>(); while(i!=s.length()) { if(!(stack.isEmpty())&&s.charAt(i)==stack.peek() ) { stack.pop(); } else {stack.push(s.charAt(i)); } i++; } if(stack.isEmpty()) {System.out.println("Yes");} else {System.out.println("No");} } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
686dede7ab8a960569a472c77538736a
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { // /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ FastReader s=new FastReader(); // push(3); // push(2); // push(1); // push(4); // push(5); //String str=s.nextLine(); //Stack<Integer> st=new Stack(); //int c=0; //int n=s.nextInt(); int i=0; Stack<Character> st=new Stack<>(); String str=s.nextLine(); // int max=0; for(i=0;i<str.length();i++){ if(!st.isEmpty() && st.peek()==str.charAt(i)){st.pop();} else{ st.push(str.charAt(i));} } if(st.isEmpty()){ System.out.println("Yes"); } else{ System.out.println("No"); }}} // String a=str.length(); // String b=str.length(); // int t=s.nextInt(); // int i; // int[] freq=new int[26]; // for(i=0;i<a.length();i++){ // freq[a.charAt(i)-'0']++; // } // for(i=0;i<b.length();i++){ // if(freq[b.charAt(i)-'0']>0){ // freq[b.charAt(i)-'0']--; // } // else{ // freq[b.charAt(i)-'0']++; // } // } // while(t-->0){ // int l,r; // String str=s.nextLine(); // l=s.nextInt(); // r=s.nextInt(); // while(i<n){ // if(str.charAt(i)==str.charAt(len)){ // //max[str.indexOf(str.charAt(i))]++; // //System.out.println(max[len]+" "+str.charAt(len)); // len++; // lps[i]=len;i++; // } // else{ // if(len!=0){ // len=lps[len-1]; // // System.out.println(len); // } // else{ // //System.out.println(len+"22 "); // i++; // } // }}int count=lps[n-1]; // if(count==0){ // System.out.println("-1"); // continue; // } // //System.out.println(lps[n-1]+" "+str.charAt(n-1)); // int k=1,j=0; // String s1=str.substring(0,count); // int rem=n-count; // //System.out.println(str.substring(count)+" "+s1.substring(count-rem)); // // if(rem<count && str.substring(count).equals(s1.substring(count-rem))){ // // System.out.println("lk"); // // k++; // // } // //int j=0; // for(i=count;i<n;i++){ // if(str.charAt(i)==s1.charAt(j)){ // j++; // } // else{ // j=lps[i]; // } // if(j==count || (j>0 && i==n-1)){ // j=0;k++; // } // } // // if(str.charAt(0)==str.charAt(count-1)){ // // k++; // // } // System.out.println(str.substring(0,count)); // System.out.println(k); // for (i = 0; i < n; i++) {ans[lps[i]]++;} // // for (i = n- 1; i > 0; i--) {ans[lps[i - 1]] += lps[i];} // for (i = 0; i <= n; i++) ans[i]++; // for(i=0;i<=n;i++){ // System.out.println(ans[i]); // } // int maxLength = -1; // int ind = 0; // for (i = 1; i < ans.length; i++) { // if (ans[i] >= maxLength) { // maxLength = ans[i]; // ind = i; // }} // // int m=max[0];int ind=0; // // for(i=1;i<n;i++){ // // //System.out.println(str.charAt(i)+" "+max[i]+" "+m); // // if(m<=max[i]){ // // m=max[i]; // // ind=i; // // } // // } // System.out.println(str.substring(0,ind)); // } // }} // } //int c=s.nextInt(); // ListNode temp=new ListNode(0); //temp.next=a; // if(a==null || a.next==null){ // return a; // } // int i=1; // ListNode t1=temp; // while(i<b){ // temp=temp.next;i++; // } // ListNode temp1=temp; // ListNode temp2=temp.next; // ListNode prev=temp.next; // ListNode st=temp.next.next; // temp.next=null; // ListNode next; // int j=c-b; // while(j>0){ // next=st.next; // st.next=prev; // prev=st; // st=next;j--; // } // temp1.next=prev; // temp2.next=st; // System.out.println(t1.next.val+" "+temp2.val); //return a; // static void push(int new_data) // { // /* 1 & 2: Allocate the Node & // Put in the data*/ // ListNode new_node = new ListNode(new_data); // /* 3. Make next of new Node as head */ // new_node.next = a; // /* 4. Move the head to point to new Node */ // a = new_node; // } // } // // static int valid(String a){ // // String[] arr=a.split("\\."); // // int i; // // // System.out.println(a+" "+arr.length); // // for(i=0;i<4;i++){ // // // System.out.println(i+" "); // // int num=Integer.parseInt(arr[i]); // // if(arr[i].length()>3 || num>255){ // // return 0; // // } // // if(arr[i].length()>1 && arr[i].charAt(0)=='0'){ // return 0; // } // // if(num!=0 && arr[i].charAt(0)=='0'){ // // return 0; // // } // } // return 1; // } //} // class Comp implements Comparator<Person>{ // public int compare(Person p1,Person p2){ // if((p1.l*p1.w)<(p2.l*p2.w)){ // return 1; // } // if((p1.l*p1.w)<(p2.l*p2.w)){ // return -1; // } // else{ // return (p1.c-p2.c); // } // } // } class Person{ int l,w; int c; public Person(int l,int w,int c){ this.l=l;this.w=w;this.c=c; }} // static long dfs(int v){ // vis[v]=true; // Iterator<Integer> it=adj[v].iterator(); // while(it.hasNext()){ // int i=it.next(); // if(!vis[i]){ // //System.out.println(v+" l"+" "+i+" "+con); // count[v]+=1+dfs(i); // // System.out.println(v+" "+count[v]); // } // }return count[v];}} 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
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
2d3d77093f1aac5195981a9ff7274998
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class Date { public static void main(String[]args)throws Exception{ BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String x=bf.readLine(); if (x.length()%2!=0) System.out.print("No"); else{ Stack<Character> y=new Stack<Character>(); y.push('a'); for(int i=0;i<x.length();i++){ if(x.charAt(i)==y.peek()){ y.pop(); } else{ y.push(x.charAt(i)); } }if(y.peek()=='a') System.out.print("Yes"); else System.out.print("No"); } }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
4b29d378dfd7d182f0b0b5faaa6fcf65
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class Date { public static void main(String[]args)throws Exception{ BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String x=bf.readLine(); if (x.length()%2!=0) System.out.print("No"); else{ Stack<Character> y=new Stack<Character>(); y.push('a'); for(int i=0;i<x.length();i++){ if(x.charAt(i)==y.peek()){ y.pop(); } else{ y.push(x.charAt(i)); } }if(y.peek()=='a') System.out.print("Yes"); else System.out.print("No"); } }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
746cea486bde56b8706aa3e2c9827f39
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class Date { public static void main(String[]args)throws Exception{ BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String x=bf.readLine(); if (x.length()%2!=0) System.out.print("No"); else{ Stack<Character> y=new Stack<Character>(); y.push('a'); for(int i=0;i<x.length();i++){ if(x.charAt(i)==y.peek()){ y.pop(); } else{ y.push(x.charAt(i)); } }if(y.peek()=='a') System.out.print("Yes"); else System.out.print("No"); } }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
00a1bf8d8cfc288054663f7696fb8f99
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; //import java.util.StringTokenizer; public class acm { public static void main(String[]args) throws Throwable{ PrintWriter out = new PrintWriter(System.out); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); //StringTokenizer st= new StringTokenizer(s); Stack<Character> a= new Stack<Character>(); for(int i =0;i<s.length();i++) { if(a.isEmpty()) a.push(s.charAt(i)); else if(a.peek()==s.charAt(i)) a.pop(); else a.push(s.charAt(i)); } String x=(a.size()==0?"Yes":"No"); out.println(x); out.flush(); out.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
d559ed08e1270e4fad910a2167b475b7
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class acm { public static void main(String[]args) throws Throwable{ PrintWriter out = new PrintWriter(System.out); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); Stack<Character> a=new Stack<Character>(); for(int i=0;i<s.length();i++) { if(a.isEmpty()) a.push(s.charAt(i)); else if(a.peek()==s.charAt(i)) a.pop(); else a.push(s.charAt(i)); } if(a.isEmpty()) out.println("Yes"); else out.println("No"); out.flush(); out.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
68b62a5a234772c86a842e27a02a4469
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; import java.util.StringTokenizer; public class Main{ public static String rev(String s){ String res=""; for (int i = s.length()-1; i >=0; i--) { res+= s.charAt(i); } return res; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s=bf.readLine(); if(s.length()==1) System.out.println("No"); else{ Stack<Character> stack= new Stack<Character>(); int c=0; for (int i = 0; i < s.length(); i++) { if(c!=0) { if(s.charAt(i)==stack.peek()){ stack.pop(); c--;} else{ stack.add(s.charAt(i)); c++;}} else{ stack.add(s.charAt(i)); c++;}} if (stack.isEmpty()) System.out.println("Yes"); else System.out.println("No"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
4a1d9bbf4628682a0d4881b4de218aec
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; /* Mighty Cohadar */ public class Bravo { public static boolean solve(char[] C) { assert C.length > 0; if (C.length % 2 != 0) { return false; } Deque<Character> Q = new ArrayDeque<>(); for (int i = 0; i < C.length; i++) { if (Q.isEmpty() == false && Q.peekFirst() == C[i]) { Q.removeFirst(); } else { Q.addFirst(C[i]); } } return Q.isEmpty(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[] C = scanner.nextLine().toCharArray(); System.out.println((solve(C)) ? "Yes" : "No"); } static void debug(Object...os) { System.err.printf("%.65536s\n", Arrays.deepToString(os)); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
6d0f8bc6bcb715a939aabcabe8f2e2de
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; public class Main { public static void main(String [] args) throws Throwable{ PrintWriter pr = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); Stack<Character> stack = new Stack<Character>(); for(int i = 0 ; i < s.length(); i++){ if(!stack.isEmpty() && stack.peek() == s.charAt(i)){ stack.pop(); } else stack.push(s.charAt(i)); } pr.println(stack.isEmpty()? "Yes" : "No"); pr.flush(); pr.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
32cf59184a60b28ecacd017d56357e7b
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; public class searching { public static void main(String[] args) { Scanner sc = new Scanner (System.in); PrintWriter pw = new PrintWriter(System.out); String s = sc.next(); if(s.length() %2 != 0) System.out.println("NO"); else { Stack<Character> st = new Stack <Character>(); st.add(s.charAt(0)); for(int i = 1 ; i<s.length() ;i++) { if (!st.isEmpty()) { if(s.charAt(i)== st.peek()) { st.pop(); } else st.add(s.charAt(i));} else st.add(s.charAt(i)); } if(st.isEmpty()) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
e10a7f7f2400fff33f1445816f22a234
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class AlternatingCurrent { static long mod = (long) Math.pow(10, 9) + 7; static FastScanner f = new FastScanner(System.in); static Scanner S = new Scanner(System.in); public static void main(String[] args)throws IOException { String s = f.next(); Stack<Character> st = new Stack<Character>(); st.push(s.charAt(0)); for(int i = 1; i < s.length(); i++) { //pn(st); if(st.size() > 0 && s.charAt(i) == st.peek()) st.pop(); else st.push(s.charAt(i)); } if(st.size() == 0) pn("Yes"); else pn("No"); } /******************************END OF MAIN PROGRAM*******************************************/ // Fast Scanner Alternative of Scanner // Uses Implementation of BufferedReader Class public static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } 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(); } String nextLine()throws IOException { return br.readLine(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // Print in console static void pn(Object o){System.out.println(o);} static void p(Object o){System.out.print(o);} static void pni(Object o){System.out.println(o);System.out.flush();} // Pair class in java static class Point implements Comparator<Point>{ int x;int y; Point(int x,int y) { this.x=x; this.y=y; } Point(){} public int compare(Point a, Point b){ if (a.x == b.x) return a.y - b.y; return a.x - b.x; } } //GCD of two integers static int gcd(int a, int b) { if(b == 0) return a; else { return gcd(b, a % b); } } // Input int array static int[] inpint(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = f.nextInt(); return arr; } //Input long array static long[] inplong(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) arr[i] = f.nextLong(); return arr; } // GCD of a array of integers static int gcdarray(int a[]) { int res = a[0]; for(int i = 1; i < a.length; i++) { res = gcd(a[i] , res); } return res; } // Return boolean sieve of first n prime nos. static boolean[] sieve(int n) { boolean isprime[] = new boolean[n + 1]; for(int i = 0; i <= n;++i) { isprime[i] = true; } isprime[0] = false; isprime[1] = false; for(int i = 2; i * i <= n; ++i) { if(isprime[i] == true) { for(int j = i * i; j <= n;j += i) isprime[j] = false; } } return isprime; } // Return HashSet of factors of a number static HashSet<Long> factors(long n) { HashSet<Long> hs = new HashSet<Long>(); for(long i = 1; i <= (long)Math.sqrt(n); i++) { if(n % i == 0) { hs.add(i); hs.add(n / i); } } return hs; } //Is n prime ? static boolean isPrime(int n) { if(n == 1) return false; int i = 2; while((i * i) <= n) { if(n % i == 0) return false; i += 1; } return true; } // Gives next (Lexicographical) permutation of String public static String nextPerm(String s) { StringBuffer sb = new StringBuffer(s); String ans = "No Successor"; int ii = -1 , jj = -1; // Largest x such that P[x] < P[x + 1] for(int i = 0; i < s.length() - 1; i++) { if((int)s.charAt(i) < (int)s.charAt(i + 1)) ii = i; } // Largest y such that P[x] < P[y] for(int j = ii + 1; j < s.length() && j != 0; j++) { if((int)s.charAt(j) > (int)s.charAt(ii)) jj = j; } if(ii == -1) return ans; else { char tempi = s.charAt(ii); char tempj = s.charAt(jj); sb.setCharAt(jj , tempi); sb.setCharAt(ii , tempj); StringBuffer sub = new StringBuffer(sb.substring(ii + 1)); sub.reverse(); int v = sub.length(); while(v-- > 0) { sb.deleteCharAt(sb.length() - 1); } sb.append(sub); ans = sb.toString(); return ans; } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
9d43660d711d1bcdaf8b9d8194624149
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.Scanner; import java.util.Stack; /* * Templates --------------- > bufstr --> BufferedReader for array input > pint --> Integer.parseInt > buf --> BufferedReader declaration > mio --> main throws IoException */ public class AlternatingCurrent { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Stack<Character> st = new Stack<>(); int n = s.length(); st.push(s.charAt(0)); char ch; for(int i = 1 ; i < n ; i++) { ch = s.charAt(i); if(!st.isEmpty() && st.peek() == ch) st.pop(); else { st.push(ch); } } System.out.println(st.isEmpty() ? "Yes" : "No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
663bf1c2c13350585fd3ab45ce0555f6
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
//package stack; import java.io.*; import java.util.*; public class AC { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); System.out.println(solve(str)); } public static String solve(String str) { Deque<Character> stack = new ArrayDeque<>(); for(char c : str.toCharArray()) { if(stack.isEmpty()) stack.push(c); else if(stack.peek() == c) { stack.pop(); } else { stack.push(c); } } return stack.isEmpty()?"Yes":"No"; } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
52a707d1dcd8b2d570f90cbe0f914f1c
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(stack.isEmpty()) { stack.push(c); }else { if(stack.peek()==c) { stack.pop(); }else { stack.push(c); } } } if(stack.empty()) { System.out.println("YES"); }else { System.out.println("NO"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
d3f7417f4ad2e8826ec861d7c646bf08
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
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 { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); String str = new String(); str=sc.next(); Stack<Character> stk = new Stack<Character>(); for(int i=0;i<str.length();i++) { if(stk.empty()) { stk.push(str.charAt(i)); } else if(str.charAt(i)==stk.peek()) { stk.pop(); } else stk.push(str.charAt(i)); } if(stk.empty()) { System.out.println("Yes"); } else { System.out.println("No"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
d1b1daa516092361382e4cfae49c132c
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.Stack; public class AlternatingCurrent { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); Stack<Character> wire = new Stack<Character>(); wire.add(s.charAt(0)); for (int i = 1; i < s.length(); i ++) { if (!(wire.isEmpty()) && s.charAt(i) == wire.peek()) wire.pop(); else wire.add(s.charAt(i)); } if (wire.isEmpty()) System.out.println("Yes"); else System.out.println("No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
7f3f6bfb295a4fc19fa93be31812041f
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.io.*; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class alternatingCurrent { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String st = bf.readLine(); Stack<Character> stack = new Stack<Character>(); stack.push(st.charAt(0)); for (int j = 1; j < st.length(); j++) { char c = st.charAt(j); if(!stack.isEmpty()){ if(stack.peek()== c) stack.pop(); else stack.push(c); } else stack.push(c); } if(stack.isEmpty()) out.println("Yes"); else out.println("No"); out.flush(); out.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
962e68e695f539c6a512358eaa46777c
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class CF343B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); char p = '+'; char n = '-'; Stack<Character> s = new Stack<Character>(); for (int i = 0; i < line.length(); i++) { char x = line.charAt(i); if(i%2 ==0){ if(x == p)x = n; else if(x == n )x = p; } if(s.isEmpty()){ s.push(x); } else if(s.peek() != x){ s.pop(); } else{ s.push(x); } } if(s.isEmpty()){ System.out.println("Yes"); } else{ System.out.println("No"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
c2ce6007878f37fa4a75744d44e1b217
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; String s = bf.readLine(); Stack<Character> stack = new Stack<Character>(); stack.add(s.charAt(0)); for (int i = 1; i < s.length() ; i++) { if (stack.size() > 0 && s.charAt(i) == stack.peek()){ stack.pop(); } else { stack.add(s.charAt(i)); } } if (stack.size() == 0){ pw.println("Yes"); } else pw.println("No"); pw.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
93b9b97405ebd6a53e525a8acc08bdb0
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; String s = bf.readLine(); Stack<Character> stack = new Stack<Character>(); stack.add(s.charAt(0)); for (int i = 1; i < s.length(); i++) { if (stack.size() > 0 && s.charAt(i) == stack.peek()) { stack.pop(); } else { stack.add(s.charAt(i)); } } if (stack.size() > 0) { System.out.println("No"); } else { System.out.println("Yes"); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
ce316d836965b061d2f1556b7831208e
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; String s = in.readLine(); int a = 0,b = 0; for(int i=0; i<s.length(); i++) { if(s.charAt(i)=='-') { if(i%2==0) a++; else b++; } else { if(i%2==0) b++; else a++; } } System.out.println(a==b ? "Yes" : "No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
f4847ed6694b0ef0af739a1ffc39af11
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); Stack<Character> stack = new Stack<>(); for (char c : s) if (stack.isEmpty() || stack.peek() != c) stack.push(c); else stack.pop(); out.println(stack.isEmpty() ? "Yes" : "No"); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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 boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
e65fb39656b0f677984d82e51f10957f
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { new a(); } public a() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = in.next(); int op1 = 0; int op2 = 0; for(int i = 0; i < s.length(); i++) { if(i%2 == 0) { if(s.charAt(i) == '-') op1++; else op2++; } else { if(s.charAt(i) == '-') op2++; else op1++; } } System.out.println((op1==op2)?"Yes":"No"); in.close(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public void close() throws IOException { br.close(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
5da2208962f9f6158cabb6d80773f37c
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayDeque; public final class Solution { public static void main(String[] args) throws IOException { solution(); } public static int LINE_LENGTH = 1000000; //No need of nextLine after integer as in Scanner 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 nextLine() throws IOException { byte[] buf = new byte[LINE_LENGTH]; // line length int cnt = 0, c; while ((c = next()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = next(); while (c <= ' ') c = next(); boolean neg = (c == '-'); if (neg) c = next(); do { ret = ret * 10 + c - '0'; } while ((c = next()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = next(); while (c <= ' ') c = next(); boolean neg = (c == '-'); if (neg) c = next(); do { ret = ret * 10 + c - '0'; } while ((c = next()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = next(); while (c <= ' ') c = next(); boolean neg = (c == '-'); if (neg) c = next(); do { ret = ret * 10 + c - '0'; } while ((c = next()) >= '0' && c <= '9'); if (c == '.') { while ((c = next()) >= '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 next() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void solution() throws IOException { Reader in = new Reader(); String exp = in.nextLine().trim(); ArrayDeque<Character> stack = new ArrayDeque<>(); for (int i = 0; i < exp.length(); i++) { if (stack.isEmpty() || stack.peek() != exp.charAt(i)) { stack.push(exp.charAt(i)); } else { stack.pop(); } } System.out.println(stack.isEmpty() ? "Yes" : "No"); in.close(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
d760592b965cfbc3bbe742a6ab219fab
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class AlternatingCurrent{ public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine(); System.out.println(canUntangle(input)); reader.close(); } public static String canUntangle(String input){ Deque<Character> stack = new LinkedList<>(); for(int i = 0; i < input.length(); i++){ if(stack.isEmpty()){ stack.push(input.charAt(i)); } else{ if(stack.peek() == input.charAt(i)){ stack.pop(); } else{ stack.push(input.charAt(i)); } } } return stack.isEmpty()? "Yes" : "No"; } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
0e167e8826754ecbeca6c8a877f7d0f7
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class chef { 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') break; 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 IOException { Scanner sc=new Scanner(System.in); String s=sc.nextLine(); Stack st=new Stack(); int ctr=1; char stk[]=new char[s.length()+1]; int top=-1; for(int i=0;i<s.length();i++) { //System.out.println("scsdc "+top); if(top!=-1) { if((s.charAt(i)==stk[top])) top--; else { top++; stk[top]=s.charAt(i); } } else { top++; stk[top]=s.charAt(i); } } //System.out.println(top); if(top==-1) System.out.println("Yes"); else System.out.println("No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
30d106633b551d60fedda145704fee2b
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class koi { public static void main(String[] args) throws Exception { int u =0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String s = br.readLine(); Stack<Character> st = new Stack<Character>(); st.add(s.charAt(0)); for (int i =1;i<s.length();i++){ if (!st.isEmpty()&&s.charAt(i)==st.peek()){ st.pop(); }else { st.push(s.charAt(i)); } } if (st.size()==0){ pw.print("YES"); }else{ pw.print("NO"); } pw.flush(); }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
e579c32bcfdd409be7ab4f57e163bd25
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class koi { public static void main(String[] args) throws Exception { int u =0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); String s = br.readLine(); Stack<Character> st = new Stack<Character>(); st.add(s.charAt(0)); for (int i =1;i<s.length();i++){ if (!st.isEmpty()&&s.charAt(i)==st.peek()){ st.pop(); }else { st.push(s.charAt(i)); } } if (st.size()==0){ pr.print("YES"); }else{ pr.print("NO"); } pr.flush(); }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
84b423efe85683b571a22ec4727d5f37
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class koi { public static void main(String[] args) throws Exception { int u =0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String s = br.readLine(); Stack<Character> st = new Stack<Character>(); st.add(s.charAt(0)); for (int i =1;i<s.length();i++){ if (!st.isEmpty()&&s.charAt(i)==st.peek()){ st.pop(); }else { st.push(s.charAt(i)); } } if (st.size()==0){ pw.print("YES"); }else{ pw.print("NO"); } pw.close(); }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
e49551c5a323e31aee0ef8c3c2ab72e2
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; public class ko { public static void main(String[] args) throws Exception { int u =0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String s = br.readLine(); Stack<Character> st = new Stack<Character>(); st.add(s.charAt(0)); for (int i =1;i<s.length();i++){ if (!st.isEmpty()&&s.charAt(i)==st.peek()){ st.pop(); }else { st.push(s.charAt(i)); } } if (st.size()==0){ pw.print("YES"); }else{ pw.print("NO"); } pw.close(); }}
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
fcaf50c3386e2c732baa5b9eeeea5aa0
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.*; public class current{ public static void main (String[]args){ Scanner sc=new Scanner (System.in); String s=sc.next(); Stack <Character> st=new Stack <Character>(); for(int i=0;i<s.length();i++){ if(st.isEmpty()==true){ st.add(s.charAt(i)); } else{ if(s.charAt(i)==st.peek()){ st.pop(); } else{ st.add(s.charAt(i)); } } } if(st.isEmpty()==true) System.out.print("Yes"); else System.out.print("No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
1f845327a6c89d4b0c31433ac26fbea9
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.*; import java.util.*; import java.awt.*; public class Main { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); StringBuilder sb=new StringBuilder(); String s=sc.next(); if((s.length()&1)==1){ System.out.println("No"); return; } int c1=0,c2=0; for(int i=0;i<s.length();i++){ if(i%2==0){ if(s.charAt(i)=='-')c1++; else c2++; } else{ if(s.charAt(i)=='-')c2++; else c1++; } } if(c1==c2) System.out.println("Yes"); else System.out.println("No"); } } 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
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
b75c32a06098c3fadacaee52659b800b
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class Dep { public static void main(String[] args) throws IOException { FastReader in = new FastReader(); String n = in.next(); char x[]=new char[n.length()+1]; // String k="i"; int f=1; for (int i = 0; i < n.length(); i++) { if(x[f-1]==n.charAt(i)) {f--;} else { x[f]=n.charAt(i); f++;} } if(f==1) System.out.println("Yes"); else System.out.println("No"); } } class FastReader { StringTokenizer st; BufferedReader br; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public boolean hasNext() throws IOException { String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s.isEmpty()) { return null; } st = new StringTokenizer(s); } return st.nextToken(); } 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(); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
a022b3e0d4cfd346d90b693a0910f331
train_001.jsonl
1379172600
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
256 megabytes
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner obj = new Scanner(System.in); String s = obj.next(); if(s.length()%2!=0) { System.out.println("No"); return; } Stack<Character> stack = new Stack<>(); for(int i=0;i<s.length();i++) { if(stack.empty()) { stack.push(s.charAt(i)); } else if(s.charAt(i)==stack.peek()) { stack.pop(); } else { stack.push(s.charAt(i)); } } if(stack.size()==0) System.out.println("Yes"); else System.out.println("No"); } }
Java
["-++-", "+-", "++", "-"]
1 second
["Yes", "No", "Yes", "No"]
NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Java 8
standard input
[ "data structures", "implementation", "greedy" ]
89b4a7b4a6160ce784c588409b6ce935
The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
1,600
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
standard output
PASSED
087d2d063ae07d8e37c9b553bed58c52
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
/* *created by Kraken on 08-05-2020 at 15:28 */ //package com.kraken.cf.practice; import java.util.*; import java.io.*; public class D459 { private static int MAXN = (int) 1e6 + 5; private static long[] BIT; private static int[] l, r; private static int n; private static void add(int x) { while (x <= n) { BIT[x]++; x += x & -x; } } private static long sum(int x) { long sum = 0; while (x > 0) { sum += BIT[x]; x -= x & -x; } return sum; } public static void main(String[] args) { FastReader sc = new FastReader(); n = sc.nextInt(); long[] x = new long[n + 1]; BIT = new long[MAXN]; l = new int[MAXN]; r = new int[MAXN]; for (int i = 1; i <= n; i++) x[i] = sc.nextInt(); Map<Long, Integer> map = new HashMap<>(); for (int i = 1; i <= n; i++) { map.put(x[i], map.getOrDefault(x[i], 0) + 1); l[i] = map.get(x[i]); } map.clear(); for (int i = n; i > 0; i--) { map.put(x[i], map.getOrDefault(x[i], 0) + 1); r[i] = map.get(x[i]); } long res = 0; for (int i = 1; i <= n; i++) { res += sum(n) - sum(r[i]); add(l[i]); } System.out.println(res); } 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
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
755399d62cd17f6c1e0b8e04382d08e2
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class CF_459_D_PASHMAK_AND_PARMIDA_PROBLEM { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] a = new int [n+1]; DataCompress data = new DataCompress(); FenwickTree ft = new FenwickTree(); HashMap<Integer ,Integer> map = new HashMap<>(); int [] prefix , suffix ; prefix = new int [n+1]; suffix = new int [n+1]; for(int i = 1 ; i <= n ; i++) { a[i] = sc.nextInt(); map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; prefix[i] = map.get(data.get(a[i])); ft.adjust(prefix[i], 1); } map = new HashMap<>(); for(int i = n ; i > 0 ; i--) { map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; suffix[i] = map.get(data.get(a[i])); } long ans = 0 ; for(int i = n ; i > 0 ; i --) { ft.adjust(prefix[i], -1); ans += ft.rsq(suffix[i] + 1, (int)1e6); } System.out.println(ans); } static class DataCompress { HashMap<Integer,Integer> map = new HashMap<>(); int idx = 1 ; void assign(int val) { map.put(val, idx++); } int get (int val) { if(map.get(val) == null) assign(val); return map.get(val); } } static class FenwickTree { int [] ft ; FenwickTree() { ft = new int [(int) 1e6 + 1]; } int rsq (int a) { int sum = 0 ; for(int b = a ; b >0 ; b -= (b&-b)) sum += ft[b]; return sum ; } int rsq(int a , int b) { return rsq(b) - rsq(a-1); } void adjust(int i , int v) { for(int k = i ; k < ft.length ; k+= (k & -k)) ft[k] += v; } } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
0c2dabe71fb05353d3de6596b7caaddc
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class CF_459_D_PASHMAK_AND_PARMIDA_PROBLEM { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long [] a = new long [n+1]; DataCompress data = new DataCompress(); SegmentTree st = new SegmentTree((int)1e6+1); HashMap<Integer ,Integer> map = new HashMap<>(); int [] prefix , suffix ; prefix = new int [n+1]; suffix = new int [n+1]; for(int i = 1 ; i <= n ; i++) { a[i] = sc.nextLong(); map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; prefix[i] = map.get(data.get(a[i])); st.updatePoint(prefix[i], 1); } map = new HashMap<>(); for(int i = n ; i > 0 ; i--) { map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; suffix[i] = map.get(data.get(a[i])); } long ans = 0 ; for(int i = n ; i > 0 ; i --) { st.updatePoint(prefix[i], -1); ans += st.query(suffix[i] , (int)1e6+1); } System.out.println(ans); } static class DataCompress { HashMap<Long,Integer> map = new HashMap<>(); int idx = 1 ; void assign(long val) { map.put(val, idx++); } int get (long val) { if(map.get(val) == null) assign(val); return map.get(val); } @Override public String toString() { return map+""; } } static class SegmentTree { int N = 1; long [] sTree , lazy ; SegmentTree (int n) { N = 1 ; while(N < n) N <<= 1 ; N -- ; sTree = new long [N << 1]; lazy = new long [N << 1] ; } void updatePoint(int idx , long val ) { idx += N - 1 ; sTree[idx] += val ; while(idx > 1) { idx >>= 1 ; sTree[idx] = sTree[idx << 1] + sTree[idx << 1 | 1] ; } } void updateRange(int i , int j , long val) { updateRange(1 , 1 , N , i , j , val ); } void updateRange(int node , int b , int e , int i , int j , long val) { if(b > j || e < i) return; if(i <= b && e <= j ) { sTree[node] += (e - b + 1) * val; lazy[node] += val ; return ; } int mid = (b+e) >> 1 ; push(node, b , mid, e); updateRange(node << 1, b, mid, i, j, val); updateRange(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1] ; } void push(int node , int b , int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1 ) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node] ; lazy[node] = 0 ; } long query(int i , int j) { return query(1 , 1 , N , i , j ); } long query(int node , int b , int e , int i , int j) { if(b > j || e < i) return 0 ; if(i <= b && e <= j) return sTree[node] ; int mid = (b + e) >> 1 ; push(node, b , mid , e); return query(node << 1, b, mid, i, j) + query(node << 1 | 1, mid + 1, e, i, j); } } static class FenwickTree { long [] ft ; FenwickTree() { ft = new long [(int) 1e6 + 1]; } long rsq (int a) { long sum = 0 ; for(int b = a ; b >0 ; b -= (b&-b)) sum += ft[b]; return sum ; } long rsq(int a , int b) { return rsq(b) - rsq(a-1); } void adjust(int i , long v) { for(int k = i ; k < ft.length ; k+= (k & -k)) ft[k] += v; } } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
745e8bf60888df849d4cb49e84ff72e4
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class CF_459_D_PASHMAK_AND_PARMIDA_PROBLEM { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] a = new int [n+1]; DataCompress data = new DataCompress(); SegmentTree st = new SegmentTree((int)1e6+1); HashMap<Integer ,Integer> map = new HashMap<>(); int [] prefix , suffix ; prefix = new int [n+1]; suffix = new int [n+1]; for(int i = 1 ; i <= n ; i++) { a[i] = sc.nextInt(); map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; prefix[i] = map.get(data.get(a[i])); st.updatePoint(prefix[i], 1); } map = new HashMap<>(); for(int i = n ; i > 0 ; i--) { map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; suffix[i] = map.get(data.get(a[i])); } long ans = 0 ; for(int i = n ; i > 0 ; i --) { st.updatePoint(prefix[i], -1); ans += st.query(suffix[i] , (int)1e6+1); } System.out.println(ans); } static class DataCompress { HashMap<Integer,Integer> map = new HashMap<>(); int idx = 1 ; void assign(int val) { map.put(val, idx++); } int get (int val) { if(map.get(val) == null) assign(val); return map.get(val); } @Override public String toString() { return map+""; } } static class SegmentTree { int N = 1; int [] sTree , lazy ; SegmentTree (int n) { N = 1 ; while(N < n) N <<= 1 ; N -- ; sTree = new int [N << 1]; lazy = new int [N << 1] ; } void updatePoint(int idx , int val ) { idx += N - 1 ; sTree[idx] += val ; while(idx > 1) { idx >>= 1 ; sTree[idx] = sTree[idx << 1] + sTree[idx << 1 | 1] ; } } void updateRange(int i , int j , long val) { updateRange(1 , 1 , N , i , j , val ); } void updateRange(int node , int b , int e , int i , int j , long val) { if(b > j || e < i) return; if(i <= b && e <= j ) { sTree[node] += (e - b + 1) * val; lazy[node] += val ; return ; } int mid = (b+e) >> 1 ; push(node, b , mid, e); updateRange(node << 1, b, mid, i, j, val); updateRange(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1] ; } void push(int node , int b , int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1 ) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node] ; lazy[node] = 0 ; } long query(int i , int j) { return query(1 , 1 , N , i , j ); } long query(int node , int b , int e , int i , int j) { if(b > j || e < i) return 0 ; if(i <= b && e <= j) return sTree[node] ; int mid = (b + e) >> 1 ; push(node, b , mid , e); return query(node << 1, b, mid, i, j) + query(node << 1 | 1, mid + 1, e, i, j); } } static class FenwickTree { int [] ft ; FenwickTree() { ft = new int [(int) 1e6 + 1]; } long rsq (int a) { long sum = 0 ; for(int b = a ; b >0 ; b -= (b&-b)) sum += ft[b]; return sum ; } long rsq(int a , int b) { return rsq(b) - rsq(a-1); } void adjust(int i , long v) { for(int k = i ; k < ft.length ; k+= (k & -k)) ft[k] += v; } } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
8ea7e057ac92e5b8c0ae1664f6e219dc
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class CF_459_D_PASHMAK_AND_PARMIDA_PROBLEM { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] a = new int [n]; HashMap<Integer,Integer> map = new HashMap<>(); Map<Integer,Integer> mapR = new HashMap<>(); int [] left = new int [n]; for(int i = 0 ; i< n ; i++) { a[i] = sc.nextInt(); map.put(a[i], map.getOrDefault(a[i], 0)+1); left[i] = map.get(a[i]); } int [] right = new int [n]; for(int i = n-1 ; i>= 0 ; i--) { mapR.put(a[i], mapR.getOrDefault(a[i], 0)+1); right[i] = mapR.get(a[i]); } long [] freq = new long [(int) (1e6+1)]; for(int i = 0 ; i< right.length ; i++) freq[right[i]]++; FenwickTree ft = new FenwickTree(freq); long ans = 0 ; for(int i = 0 ; i < n ; i++) { int x = left[i]; ft.adjust(right[i], -1); ans += ft.rsq(x-1); } System.out.println(ans); } static class FenwickTree{ long [] ft ; FenwickTree( long [] a) { ft = new long [a.length]; for(int i = 1 ; i< a.length ; i++) adjust(i, a[i]); } long rsq (int a) { long sum = 0 ; for(int b = a ; b >0 ; b -= (b&-b)) { sum += ft[b]; } return sum ; } long rsq(int a , int b) { return rsq(b) - rsq(a-1); } void adjust(int i , long v) { for(int k = i ; k < ft.length ; k+= (k & -k)) { ft[k] += v; } } } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
f81d23936674952073e90fcda9622523
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class CF_459_D_PASHMAK_AND_PARMIDA_PROBLEM { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long [] a = new long [n+1]; DataCompress data = new DataCompress(); FenwickTree ft = new FenwickTree(); int [] freq = new int [(int) 1e6 + 1]; HashMap<Integer ,Integer> map = new HashMap<>(); int [] prefix , suffix ; prefix = new int [n+1]; suffix = new int [n+1]; for(int i = 1 ; i <= n ; i++) { a[i] = sc.nextLong(); map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; prefix[i] = map.get(data.get(a[i])); ft.adjust(prefix[i], 1); } map = new HashMap<>(); for(int i = n ; i > 0 ; i--) { map.put(data.get(a[i]), map.getOrDefault(data.get(a[i]), 0) + 1) ; suffix[i] = map.get(data.get(a[i])); } long ans = 0 ; for(int i = n ; i > 0 ; i --) { ft.adjust(prefix[i], -1); ans += ft.rsq(suffix[i] + 1, (int)1e6); } System.out.println(ans); } static class DataCompress { HashMap<Long,Integer> map = new HashMap<>(); int idx = 1 ; void assign(long val) { map.put(val, idx++); } int get (long val) { if(map.get(val) == null) assign(val); return map.get(val); } @Override public String toString() { return map+""; } } static class FenwickTree { long [] ft ; FenwickTree() { ft = new long [(int) 1e6 + 1]; } long rsq (int a) { long sum = 0 ; for(int b = a ; b >0 ; b -= (b&-b)) sum += ft[b]; return sum ; } long rsq(int a , int b) { return rsq(b) - rsq(a-1); } void adjust(int i , long v) { for(int k = i ; k < ft.length ; k+= (k & -k)) ft[k] += v; } } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
fc5b14f952c338b877957184f10aa6fa
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; private 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; } } static class Pair<U, V> { private final U first; // first field of a Pair private final V second; // second field of a Pair // Constructs a new Pair with specified values private Pair(U first, V second) { this.first = first; this.second = second; } @Override // Checks specified object is "equal to" current object or not public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; // call equals() method of the underlying objects if (!first.equals(pair.first)) return false; return second.equals(pair.second); } @Override // Computes hash code for an object to support hash tables public int hashCode() { // use hash codes of the underlying objects return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return "(" + first + ", " + second + ")"; } // Factory method for creating a Typed Pair immutable instance public static <U, V> Pair <U, V> of(U a, V b) { // calls private constructor return new Pair<>(a, b); } } public static void update(int x, int val){ for(;x<tree.length; x+=x&(-x)){ tree[x]+=val; } } public static int query(int x){ int res=0; for(;x>0; x-=x&(-x)){ res+= tree[x]; } return res; } static int[] tree; static int[] ar; static int[] fo; static int[] rev; public static void main(String[] args) throws IOException { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n=in.nextInt(); ar= new int[n+1]; fo= new int[n+1]; rev= new int[n+1]; int[] arr= new int[n+1]; for(int i=1; i<=n;i++){ arr[i]=in.nextInt(); } Map<Integer,Integer> map =new HashMap<>(); for(int i=1; i<=n;i++){ map.put(arr[i], map.getOrDefault(arr[i],0)+1); fo[i]=map.get(arr[i]); } map.clear(); for(int i=n; i>0;i--){ map.put(arr[i], map.getOrDefault(arr[i],0)+1); rev[i]=map.get(arr[i]); } tree= new int[n+1]; for(int i=1 ;i<=n;i++){ update(rev[i],1); } long res=0; for(int i=1 ;i<=n; i++){ update(rev[i],-1); res+= query(fo[i]-1); } out.println(res); out.flush(); out.close(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
c9e04d6ff735e315f3d89fdc40383388
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class PASHMAK_AND_PARMIDA_PROBLEM { public static long count = 0; public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = s.nextInt(); } int[][] freq = new int[2][n]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<n;i++) { int v = arr[i]; if(map.containsKey(v)) { int c = map.get(v); freq[0][i] = c + 1; map.put(v, c + 1); } else { freq[0][i] = 1; map.put(v, 1); } } map = new HashMap<>(); for(int i=n-1;i>=0;i--) { int v = arr[i]; if(map.containsKey(v)) { int c = map.get(v); freq[1][i] = c + 1; map.put(v, c + 1); } else { freq[1][i] = 1; map.put(v, 1); } } getCount(freq, 0, n-1); System.out.println(count); } public static int[][] getCount(int[][] arr, int low, int high) { int n = high - low + 1; if(low == high) { int[][] ar = new int[2][1]; ar[0][0] = arr[0][low]; ar[1][0] = arr[1][low]; return ar; } int mid = (low + high)/2; int[][] ar1 = getCount(arr, low, mid); int[][] ar2 = getCount(arr, mid + 1, high); int i = 0, j = 0; int[][] ar = new int[2][n]; //System.out.println(n); // print(ar1[0]); // print(ar2[1]); while(i < ar1[0].length && j < ar2[0].length) { //System.out.println(i+" "+j); if(ar1[0][i] <= ar2[1][j]) { count += j; i++; } else { j++; } } while(i < ar1[0].length) { count += ar2[0].length; //System.out.println("count = "+count); i++; } merge(ar[0], ar1[0], ar2[0]); merge(ar[1], ar1[1], ar2[1]); return ar; } public static void merge(int[] ar, int[] ar1, int[] ar2) { int index = 0, i = 0, j = 0; while(i < ar1.length && j < ar2.length) { if(ar1[i] < ar2[j]) { ar[index++] = ar1[i++]; } else { ar[index++] = ar2[j++]; } } while(i < ar1.length) { ar[index++] = ar1[i++]; } while(j < ar2.length) { ar[index++] = ar2[j++]; } } public static void print(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
662968592f0c248207f301aa484c0aae
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class PASHMAK_AND_PARMIDA_PROBLEM { public static long count = 0; public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; int max = 0; for(int i=0;i<n;i++) { arr[i] = s.nextInt(); } int[][] freq = new int[2][n]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<n;i++) { int v = arr[i]; if(map.containsKey(v)) { int c = map.get(v); freq[0][i] = c + 1; map.put(v, c + 1); } else { freq[0][i] = 1; map.put(v, 1); } } map = new HashMap<>(); for(int i=n-1;i>=0;i--) { int v = arr[i]; if(map.containsKey(v)) { int c = map.get(v); freq[1][i] = c + 1; map.put(v, c + 1); } else { freq[1][i] = 1; map.put(v, 1); } max = Math.max(max, freq[1][i]); } // USING DIVIDE AND CONQUER: // getCount(freq, 0, n-1); // System.out.println(count); // USING FENWICK TREE: //System.out.println("max = "+max); int[] bit = new int[max + 1]; //System.out.println(count); for(int i=n-1;i>=0;i--) { int sum = getSum(bit, freq[0][i] - 1); //System.out.println(sum); count += sum; update(bit, freq[1][i], 1); } System.out.println(count); } public static int getSum(int[] bit, int index) { int sum = 0; while(index > 0) { sum += bit[index]; index -= (index & (-index)); } return sum; } public static void update(int[] bit, int index, int val) { int n = bit.length; while(index < n) { bit[index] += val; index += (index & (-index)); } } public static int[][] getCount(int[][] arr, int low, int high) { int n = high - low + 1; if(low == high) { int[][] ar = new int[2][1]; ar[0][0] = arr[0][low]; ar[1][0] = arr[1][low]; return ar; } int mid = (low + high)/2; int[][] ar1 = getCount(arr, low, mid); int[][] ar2 = getCount(arr, mid + 1, high); int i = 0, j = 0; int[][] ar = new int[2][n]; //System.out.println(n); // print(ar1[0]); // print(ar2[1]); while(i < ar1[0].length && j < ar2[0].length) { //System.out.println(i+" "+j); if(ar1[0][i] <= ar2[1][j]) { count += j; i++; } else { j++; } } while(i < ar1[0].length) { count += ar2[0].length; //System.out.println("count = "+count); i++; } merge(ar[0], ar1[0], ar2[0]); merge(ar[1], ar1[1], ar2[1]); return ar; } public static void merge(int[] ar, int[] ar1, int[] ar2) { int index = 0, i = 0, j = 0; while(i < ar1.length && j < ar2.length) { if(ar1[i] < ar2[j]) { ar[index++] = ar1[i++]; } else { ar[index++] = ar2[j++]; } } while(i < ar1.length) { ar[index++] = ar1[i++]; } while(j < ar2.length) { ar[index++] = ar2[j++]; } } public static void print(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
02e58061218dc746401da1704f7d6362
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class l075 { public static void main(String[] args) throws Exception { // StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next()); StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); Integer n = Integer.parseInt(stok.nextToken()); int[] a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = Integer.parseInt(stok.nextToken()); HashMap<Integer,Integer> fmp = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> rmp = new HashMap<Integer,Integer>(); int[] famp = new int[n+1]; long[] fen = new long[n+1]; for(int i=1;i<=n;i++) famp[i] = incMap(fmp,a[i]); long tot = 0; for(int i=n;i>0;i--) { tot += fenwickQ(famp[i]-1,fen); int v = incMap(rmp,a[i]); fenwickI(v,1,fen); } System.out.println(tot); } private static void fenwickI(int id, int v, long[] fen) { int l = fen.length; for(int i=id;i<l;i+=i&-i) { fen[i] += v; } } private static long fenwickQ(int id, long[] fen) { long ret = 0; for(int i=id;i>0;i-=i&-i) { ret += fen[i]; } return ret; } private static int incMap(HashMap<Integer, Integer> mp, int k) { Integer v = mp.get(k); v = v==null?1:v+1; mp.put(k, v); return v; } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
d42e5763e9678d8a920e90e53cfd54fd
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class PashmakAndParmidaproblem { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { long mod = (long)(998244353l); public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { while(testNumber-->0){ int n = in.nextInt(); long a[] = new long[n+1]; for(int i=1;i<=n;i++) a[i] = in.nextLong(); HashMap<Long , Integer> left = new HashMap<>(); HashMap<Long , Integer> right = new HashMap<>(); int fLeft[] = new int[n+1]; int fRight[] = new int[n+1]; for(int i=1;i<=n;i++){ long x = a[i]; if(left.containsKey(x)) left.put(x , left.get(x) + 1); else left.put(x , 1); fLeft[i] = left.get(x); } // for(int i=1;i<=n;i++) // System.out.print(fLeft[i] + " "); // System.out.println(); int BIT[] = new int[n+1]; for(int i=n;i>=1;i--){ long x = a[i]; if(right.containsKey(x)) right.put(x , right.get(x)+1); else right.put(x , 1); fRight[i] = right.get(x); BIT(BIT , fRight[i] , 1); } // for(int i=1;i<=n;i++) // System.out.print(fRight[i] + " "); // System.out.println(); // for(int i=1;i<=n;i++) // System.out.print(BIT[i] + " "); // System.out.println(); long ans = 0; for(int i=1;i<=n;i++){ // System.out.println("aaaaa"); BIT(BIT , fRight[i] , -1); // System.out.println("bbbbb"); ans += ans(BIT , fLeft[i]-1); } out.println(ans); } } public long ans(int a[] , int index){ long sum = 0; for(int i=index;i>=1;i-=(i)&(-i)){ sum += a[i]; // System.out.println(i); } return sum; } public void BIT(int a[] , int index , int val){ for(int i = index;i<a.length && i>0;i+=i&(-i)){ a[i]+=val; // System.out.println(i); } } public long cal(ArrayList<Long> a , long n){ long x = (1 + (long)Math.sqrt(1+8*n))/2; a.add(x); n -= (x*(x-1))/2; // System.out.println(n); return n; } public void sieve(int a[]){ a[0] = a[1] = 1; int i; for(i=2;i*i<=a.length;i++){ if(a[i] != 0) continue; a[i] = i; for(int k = (i)*(i);k<a.length;k+=i){ if(a[k] != 0) continue; a[k] = i; } } } public int [][] matrixExpo(int c[][] , int n){ int a[][] = new int[c.length][c[0].length]; int b[][] = new int[a.length][a[0].length]; for(int i=0;i<c.length;i++) for(int j=0;j<c[0].length;j++) a[i][j] = c[i][j]; for(int i=0;i<a.length;i++) b[i][i] = 1; while(n!=1){ if(n%2 == 1){ b = matrixMultiply(a , a); n--; } a = matrixMultiply(a , a); n/=2; } return matrixMultiply(a , b); } public int [][] matrixMultiply(int a[][] , int b[][]){ int r1 = a.length; int c1 = a[0].length; int c2 = b[0].length; int c[][] = new int[r1][c2]; for(int i=0;i<r1;i++){ for(int j=0;j<c2;j++){ for(int k=0;k<c1;k++) c[i][j] += a[i][k]*b[k][j]; } } return c; } public long nCrPFermet(int n , int r , long p){ if(r==0) return 1l; long fact[] = new long[n+1]; fact[0] = 1; for(int i=1;i<=n;i++) fact[i] = (i*fact[i-1])%p; long modInverseR = pow(fact[r] , p-2 , 1l , p); long modInverseNR = pow(fact[n-r] , p-2 , 1l , p); long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p; return w; } public long pow(long a , long b , long res , long mod){ if(b==0) return res; if(b==1) return (res*a)%mod; if(b%2==1){ res *= a; res %= mod; b--; } // System.out.println(a + " " + b + " " + res); return pow((a*a)%mod , b/2 , res , mod); } public long pow(long a , long b , long res){ if(b == 0) return res; if(b==1) return res*a; if(b%2==1){ res *= a; b--; } return pow(a*a , b/2 , res); } public void swap(int a[] , int p1 , int p2){ int x = a[p1]; a[p1] = a[p2]; a[p2] = x; } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ long value; long delete; Combine(long val , long delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(b == 0) return a; return gcd(b , a%b); } public void print2d(long a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } } 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()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
60e810f2580911f2410e51c978792ea4
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
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.StringTokenizer; import java.util.TreeMap; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), a[] = new int[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextInt(); FenwickTree ft = new FenwickTree(n); TreeMap<Integer, Integer> freq = new TreeMap<>(); int[] fsuffix = new int[n]; for(int i = n - 1; i >= 0; --i) { Integer f = freq.get(a[i]); if(f == null) f = 0; fsuffix[i] = ++f; freq.put(a[i], f); ft.update(f, 1); } freq.clear(); long ans = 0; for(int i = 0; i < n; ++i) { ft.update(fsuffix[i], -1); Integer f = freq.get(a[i]); if(f == null) f = 0; freq.put(a[i], ++f); ans += ft.query(f - 1); } out.println(ans); out.flush(); out.close(); } static class FenwickTree { int[] ft; FenwickTree(int n) { ft = new int[n + 1]; } void update(int idx, int val) { while(idx < ft.length) { ft[idx] += val; idx += idx & -idx; } } int query(int idx) { int s = 0; while(idx > 0) { s += ft[idx]; idx ^= idx & -idx; } return s; } } 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 int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
5137ab40134a2b347c459c530a5e4d06
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
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.HashMap; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), a[] = new int[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextInt(); FenwickTree ft = new FenwickTree(n); HashMap<Integer, Integer> freq = new HashMap<>(); int[] fsuffix = new int[n]; for(int i = n - 1; i >= 0; --i) { Integer f = freq.get(a[i]); if(f == null) f = 0; fsuffix[i] = ++f; freq.put(a[i], f); ft.update(f, 1); } freq.clear(); long ans = 0; for(int i = 0; i < n; ++i) { ft.update(fsuffix[i], -1); Integer f = freq.get(a[i]); if(f == null) f = 0; freq.put(a[i], ++f); ans += ft.query(f - 1); } out.println(ans); out.flush(); out.close(); } static class FenwickTree { int[] ft; FenwickTree(int n) { ft = new int[n + 1]; } void update(int idx, int val) { while(idx < ft.length) { ft[idx] += val; idx += idx & -idx; } } int query(int idx) { int s = 0; while(idx > 0) { s += ft[idx]; idx ^= idx & -idx; } return s; } } 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 int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
ce0c6bd5b7aa6b3ed1ab7696bb50193b
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nasko */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int[] elem = new int[N]; int[] left = new int[N]; int[] right = new int[N]; HashMap<Integer, Integer> a = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> b = new HashMap<Integer, Integer>(); TaskD.Fenwick ft = new TaskD.Fenwick(N + 5); for (int i = 0; i < N; ++i) { elem[i] = in.nextInt(); if (!a.containsKey(elem[i])) { a.put(elem[i], 1); } else a.put(elem[i], a.get(elem[i]) + 1); left[i] = a.get(elem[i]); } for (int i = N - 1; i >= 0; --i) { if (!b.containsKey(elem[i])) { b.put(elem[i], 1); } else { b.put(elem[i], b.get(elem[i]) + 1); } right[i] = b.get(elem[i]); } long ans = 0L; for (int i = N - 1; i >= 0; --i) { ans += ft.get(left[i] - 1); ft.add(1, right[i], N); } out.println(ans); } static class Fenwick { int N; int[] sum; public Fenwick(int _N) { N = _N; sum = new int[_N]; } public void add(int value, int index, int limit) { while (index < limit) { sum[index] += value; index += (index & (-index)); } } public long get(int index) { long ret = 0L; while (index > 0) { ret += sum[index]; index -= (index & (-index)); } return ret; } } } 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()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
daa6c6598590ac0311e3d5b58b90b13b
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nasko */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int[] elem = new int[N]; int[] left = new int[N]; int[] right = new int[N]; HashMap<Integer, Integer> a = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> b = new HashMap<Integer, Integer>(); TaskD.Fenwick ft = new TaskD.Fenwick(N + 5); for (int i = 0; i < N; ++i) { elem[i] = in.nextInt(); if (!a.containsKey(elem[i])) { a.put(elem[i], 1); } else a.put(elem[i], a.get(elem[i]) + 1); left[i] = a.get(elem[i]); } for (int i = N - 1; i >= 0; --i) { if (!b.containsKey(elem[i])) { b.put(elem[i], 1); } else { b.put(elem[i], b.get(elem[i]) + 1); } right[i] = b.get(elem[i]); } long ans = 0L; for (int i = N - 1; i >= 0; --i) { ans += ft.get(left[i] - 1); ft.add(1, right[i]); } out.println(ans); } static class Fenwick { int N; int[] sum; public Fenwick(int _N) { N = _N; sum = new int[_N]; } public void add(int value, int index) { while (index < sum.length - 5) { sum[index] += value; index += (index & (-index)); } } public long get(int index) { long ret = 0L; while (index > 0) { ret += sum[index]; index -= (index & (-index)); } return ret; } } } 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()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
2a6f256c28cd0b04c82f88935f580001
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author Bat-Orgil */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { static int[] A; static void add(int ind, int val, int a,int b, int n){ if(ind<a || ind>b) return; if(a==b) { A[n] += val; return; } int m = (a+b)/2; add(ind,val,a,m,2*n); add(ind,val,m+1,b,2*n+1); A[n]= A[2*n] + A[2*n+1]; } static int query(int l, int r, int a, int b, int n){ if(r<a || l>b) return 0; if(l<=a && b<= r) return A[n]; int m = (a+b)/2; int sum1= query(l,r,a,m,2*n); int sum2= query(l,r,m+1,b,2*n+1); return sum1+sum2; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n= in.nextInt(); int[] ar= new int[n]; for(int i=0; i<n; i++){ ar[i]=in.nextInt(); } HashMap<Integer, Integer> repLeft = new HashMap(); HashMap<Integer, Integer> repRight= new HashMap(); long answer=0; int[] left= new int[n]; int[] right= new int[n]; for(int i=0; i<n; i++){ if(repLeft.containsKey(ar[i])){ repLeft.put(ar[i], repLeft.get(ar[i])+1); }else{ repLeft.put(ar[i],1); } left[i]= repLeft.get(ar[i]); } for(int j=n-1; j>=0; j--){ if(repRight.containsKey(ar[j])){ repRight.put(ar[j], repRight.get(ar[j])+1); }else{ repRight.put(ar[j],1); } right[j]= repRight.get(ar[j]); } A= new int[4*n]; for(int i=n-1; i>=0; i--){ int c= left[i]; answer += query(1,c-1, 1,n, 1); add( right[i],1,1,n,1); } out.println(answer); } } 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()); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
3c375d45e98aa65d0d446cebc1071160
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class segTree { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); Pair[] left = calc_left(arr); Pair[] right = calc_right(arr); // System.out.println(Arrays.toString(left)); // System.out.println(Arrays.toString(right)); int size = 1; while(size<n) size<<=1; int[] b = new int[size + 1]; SegmentTree st = new SegmentTree(b); long ans= 0; for(int i=0, j=0; i<n;i++) { while(j<n && right[j].count<left[i].count) { st.update_point(right[j].idx, 1); j++; } ans += st.query(left[i].idx + 1, size); } out.println(ans); out.close(); } private static Pair[] calc_left(int[] arr) { HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>(); int n =arr.length; Pair left[] =new Pair[n]; for(int i=0;i<n;i++) { left[i] = new Pair(freq.getOrDefault(arr[i], 0) + 1, i+1); freq.put(arr[i],left[i].count); } Arrays.parallelSort(left); return left; } private static Pair[] calc_right(int[] arr) { HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>(); int n =arr.length; Pair right[] =new Pair[n]; for(int i=n-1;i>=0;i--) { right[i] = new Pair(freq.getOrDefault(arr[i], 0) + 1, i+1); freq.put(arr[i],right[i].count); } Arrays.parallelSort(right); return right; } static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero // lazy = new int[N << 1]; // build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] + sTree[index << 1 | 1]; } } void update_range(int i, int j) // O(log n) { update_range(1, 1, N, i, j); } void update_range(int node, int b, int e, int i, int j) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] = (e - b + 1) - sTree[node]; lazy[node] += 1; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j); update_range(node << 1 | 1, mid + 1, e, i, j); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; if (lazy[node] % 2 == 1) { sTree[node << 1] = (mid - b + 1) - sTree[node << 1]; sTree[node << 1 | 1] = (e - mid) - sTree[node << 1 | 1]; } lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 + q2; } } static class Pair implements Comparable<Pair>{ int count; int idx; public Pair(int vol, int idx) { this.count = vol; this.idx = idx; } @Override public int compareTo(Pair o) { int res = count- o.count; if(res == 0) return o.idx - idx; return res; } } 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 int nextInt() throws IOException { return Integer.parseInt(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(); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
8a84e0fa1b0daa2d36fc893dcf820e8e
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class Main { 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[100001]; // 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 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 int query(int idx,int fenwick[]){ if(idx==0)return 0; int ans=0; while(idx!=0){ ans+=fenwick[idx]; idx-=(idx&-idx); } return ans; } static void update(int idx,int fenwick[],int v,int max){ if(idx==0)return; while(idx<=max){ fenwick[idx]+=v; idx+=(idx&-idx); } } public static void main(String[] args) throws IOException { Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out); int n=s.nextInt(),i,j; int a[]=new int[n]; for(i=0;i<n;i++){ a[i]=s.nextInt(); } HashMap<Integer,Integer> hmf=new HashMap<Integer,Integer>(); HashMap<Integer,Integer> hmb=new HashMap<Integer,Integer>(); int f[]=new int[n];int b[]=new int[n]; for(i=0;i<n;i++){ if(hmf.get(a[i])==null)hmf.put(a[i],1); else hmf.put(a[i],hmf.get(a[i])+1); f[i]=hmf.get(a[i]); } for(i=n-1;i>=0;i--){ if(hmb.get(a[i])==null)hmb.put(a[i],1); else hmb.put(a[i],hmb.get(a[i])+1); b[i]=hmb.get(a[i]); } int fenwick[]=new int[n+1]; long ans=0; for(i=n-2;i>=0;i--){ update(b[i+1],fenwick,1,n); ans+=query(f[i]-1,fenwick); } pw.write(String.valueOf(ans)); pw.flush();pw.close(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
47d3360e7707b5a0fd2552c8f8b55253
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class Main { 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[100001]; // 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 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 IOException { Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out); int n=s.nextInt(),i,j; int a[]=new int[n]; for(i=0;i<n;i++){ a[i]=s.nextInt(); } HashMap<Integer,Integer> hmf=new HashMap<Integer,Integer>(); HashMap<Integer,Integer> hmb=new HashMap<Integer,Integer>(); int f[]=new int[n];int b[]=new int[n]; for(i=0;i<n;i++){ if(hmf.get(a[i])==null)hmf.put(a[i],1); else hmf.put(a[i],hmf.get(a[i])+1); f[i]=hmf.get(a[i]); } for(i=n-1;i>=0;i--){ if(hmb.get(a[i])==null)hmb.put(a[i],1); else hmb.put(a[i],hmb.get(a[i])+1); b[i]=hmb.get(a[i]); } int frq[]=new int[n+1]; long ans=0;int pvt=f[n-1],count;frq[b[n-1]]++; if(f[n-1]>b[n-1])count=1; else count=0; for(i=n-2;i>=0;i--){ if(f[i]>pvt){ for(j=pvt;j<f[i];j++)count+=frq[j]; ans+=(long)count; } else if(f[i]<pvt){ for(j=pvt-1;j>=f[i];j--){ count-=frq[j]; } ans+=(long)count; } else ans+=(long)count; if(f[i]>b[i])count++; pvt=f[i];frq[b[i]]++; } pw.write(String.valueOf(ans)); pw.flush();pw.close(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
cd8da921f33225c9014c87bf7d0a39e3
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.io.*; public class PashmakParmidasProblem { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int n = scanner.nextInt(); int[] arr = new int[n]; // TreeSet<Integer> set = new TreeSet<>(); for(int i = 0; i < n;i++) { arr[i] = scanner.nextInt(); // set.add(arr[i]); } int[] forward = new int[n]; int[] rev = new int[n]; int max = 0; HashMap<Integer,Integer> prev = new HashMap<>(); for(int i = 0; i <n; i++) { Integer other = prev.get(arr[i]); if (other != null) { forward[i] = forward[other] + 1; } else { forward[i] = 1; } max = Math.max(forward[i], max); prev.put(arr[i], i); } prev.clear(); for(int i = n-1; i >= 0; i--) { Integer other = prev.get(arr[i]); if (other != null) { rev[i] = rev[other] + 1; } else { rev[i] = 1; } max = Math.max(rev[i], max); prev.put(arr[i], i); } BIT bit = new BIT(max + 5); bit.update(forward[0], 1); long ans = 0; for(int i = 1; i < n; i++) { ans += bit.range(rev[i] + 1, max + 4); bit.update(forward[i],1); } out.println(ans); out.flush(); } static class BIT { long[] table; int sz; public BIT(int ss) { sz = ss; table = new long[ss]; } void update(int loc, long amt) { while(loc < sz) { table[loc] += amt; loc += loc & - loc; } } long pref(int loc) { long ret = 0; while(loc > 0) { ret += table[loc]; loc -= loc & - loc; } return ret; } long range(int l, int r) { return pref(r) - pref(l - 1); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
9b7291fc245384e7cbd49ebf3ce2077f
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; // author: Prajogo Tio public class Pashmak { // at index i, static int l[]; static int r[]; static int low[]; static int high[]; static int count[]; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); l = new int[n]; r = new int[n]; low = new int[1000001 * 4]; high = new int[1000001 * 4]; count = new int[1000001 * 4]; int[] rel = new int[n]; for(int i=0; i<n; i++) { rel[i] = in.nextInt(); } // number / freq Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<n; i++) { int cur = rel[i]; if(!map.containsKey(cur)) { map.put(cur, 1); } else { map.put(cur, map.get(cur) + 1); } l[i] = map.get(cur); } map.clear(); for(int i=n-1; i>=0; i--) { int cur = rel[i]; if(!map.containsKey(cur)) { map.put(cur, 1); } else { map.put(cur, map.get(cur) + 1); } r[i] = map.get(cur); } init(1, 0, n-1); long res = 0; for(int i=n-1; i>=1; i--) { update(1, r[i], r[i]); // we need atleast 1 occurence res += find(1, 1,l[i-1]-1); } System.out.println(res); } private static int find(int i, int l, int r) { if(low[i] > r || high[i] < l) { return 0; } else if(low[i] >= l && high[i] <= r) { return count[i]; } return find(2*i, l, r) + find(2*i+1, l, r); } private static void update(int i, int l, int r) { if(low[i] > r || high[i] < l) { return; } else if(low[i] == l && high[i] == r) { count[i]++; return; } update(2*i, l, r); update(2*i + 1, l, r); count[i] = count[2*i] + count[2*i + 1]; } private static void init(int i, int l, int r) { low[i] = l; high[i] = r; if(l == r) { return; } int mid = (l + r)/2; init(2*i, l, mid); init(2*i + 1, mid+1, r); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
d791d3a2adf3dfbd027e266d6d09f307
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; public class A { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int [] a = new int[n]; HashMap<Integer, Integer> pre = new HashMap<>(); HashMap<Integer, Integer> suff = new HashMap<>(); for (int i = 0; i < a.length; ++i) { a[i] = sc.nextInt(); pre.put(a[i], pre.getOrDefault(a[i], 0)+1); } long ans = 0; FenwickTree ft = new FenwickTree(n); for (int i = n-1; i >= 0; --i) { int f = pre.getOrDefault(a[i], 0); ans += ft.rsq(f); if(f > 1) pre.put(a[i], f-1); else pre.remove(a[i]); suff.put(a[i], suff.getOrDefault(a[i], 0)+1); ft.point_update(suff.getOrDefault(a[i], 0)+1, 1); } out.println(ans); out.flush(); out.close(); } 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 > 0) { sum += ft[b]; b -= b & -b;} //min? return sum; } void point_update(int k, int val) //O(log n), update = increment { while(k <= n) { ft[k] += val; k += k & -k; } //min? } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public Scanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
447403c7f46c90012c269b3539717f3a
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class H { public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(); int [] a = new int[n], numBk = new int[n]; FenwickTree ft = new FenwickTree((int)1e6); for (int i = 0; i < n; i++) { a[i] = bf.nextInt(); } HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = n-1; i >= 0; i--) { Integer tmp = mp.get(a[i]); if(tmp == null) tmp = 0; mp.put(a[i], tmp+1); numBk[i] = tmp+1; ft.point_update(tmp+1, 1); } mp.clear(); long ans = 0; for (int i = 0; i < n-1; i++) { Integer tmp = mp.get(a[i]); if(tmp == null) tmp = 0; mp.put(a[i], tmp+1); ft.point_update(numBk[i], -1); if(tmp >= 1) ans += ft.rsq(1, tmp); } out.println(ans); out.flush(); out.close(); } static class FenwickTree { int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n+1]; } int rsq(int b) { int sum = 0; while(b > 0) { sum += ft[b]; b -= b & -b;} return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a-1); } void point_update(int k, int val) { while(k <= n) { ft[k] += val; k += k & -k; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(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(); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
7e941f390b814479604d02c094d5baf4
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Cf459D { FastScanner sc; int n, mv; int[] A, L, C; Map<Integer, Integer> M; BIT B; public static void main(String[] args) { Cf459D cf = new Cf459D(); System.out.println(cf.run()); } private int getValue(int i) { if (M.containsKey(i)) return M.get(i); M.put(i, mv); return mv++; } Cf459D() { sc = new FastScanner(); mv = 0; n = sc.nextInt(); A = new int[n]; L = new int[n]; C = new int[n]; M = new TreeMap<Integer, Integer>(); B = new BIT(n); for (int i = 0; i < n; ++i) A[i] = getValue(sc.nextInt()); } public long run() { long ans = 0; for (int i = 0; i < n; ++i) L[i] = ++C[A[i]]; C = new int[n]; for (int i = n - 1; i >= 0; --i) { ans += B.query(L[i]-1); B.update(++C[A[i]]); } return ans; } public class BIT { int[] A; BIT(int n) { A = new int[n+1]; } public int query(int idx) { int ans = 0; while (idx > 0) { ans += A[idx]; idx -= idx & -idx; } return ans; } public void update(int idx) { update(idx, 1); } public void update(int idx, int val) { while (idx <= n) { A[idx] += val; idx += idx & -idx; } } } public class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
67387f30845a60b8aabcb147bb8b5ae6
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /* https://codeforces.com/contest/459/problem/D */ public class PashmakandParmidasProblem { private static int[] segmentArr; // 0 is not used, 1 to n-1 are internal nodes, n to 2n-1 are leaves private static int[] auxx; private static void preCompute() { int n = auxx.length; System.arraycopy(auxx, 0, segmentArr, n, n); for (int i = n - 1; i >= 1; i--) { segmentArr[i] = segmentArr[i << 1] + segmentArr[(i << 1) + 1]; } } private static void update(int idx) { int n = auxx.length; for (segmentArr[idx += n]--; idx > 1; idx >>= 1) segmentArr[idx >> 1] = segmentArr[idx] + segmentArr[idx ^ 1]; } private static int query(int l, int r) { // even => left child, odd => right child, [l, r) int res = 0, n = auxx.length; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) == 1) res += segmentArr[l++]; if ((r & 1) == 1) res += segmentArr[--r]; } return res; } public static void main(String[] args) throws Exception { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int[] input = new int[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) input[i] = Integer.parseInt(st.nextToken()); int[] left = new int[n], right = new int[n]; computeLeftAndRightView(left, right, input); auxx = new int[n + 1]; // max frequency be n, when all same, min be 1 [0, n] for (int i = 0; i < n; i++) auxx[right[i]]++; segmentArr = new int[2 * n + 2]; preCompute(); long result = 0; for (int i = 0; i < n; i++) { update(right[i]); // remove right[i] from segment result += query(0, left[i]); // find count of elements less than left[i] } System.out.println(result); } private static void computeLeftAndRightView(int[] left, int[] right, int[] input) { Map<Integer, Integer> frequency = new HashMap<>(); for (int i = 0; i < input.length; i++) { int count = frequency.getOrDefault(input[i], 0) + 1; frequency.put(input[i], count); left[i] = count; } frequency.clear(); for (int i = input.length - 1; i >= 0; i--) { int count = frequency.getOrDefault(input[i], 0) + 1; frequency.put(input[i], count); right[i] = count; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
71707eef3e37a0c45fc892f2429144d8
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import static java.lang.Math.*; public class Main { static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } static int n; static class SegmentTree { private int[] st; protected SegmentTree() { int x = (int) (ceil(log(n) / log(2))); int max_size = 2*(int)pow(2, x) - 1; st = new int[max_size]; } protected void update(int ind) { updateUTIL(0, 0, n-1, ind); } private void updateUTIL(int sti, int sts, int ste, int ind) { if (ind<sts || ind>ste) return; else if (sts == ste) st[sti]++; else { int mid = (sts+ste)/2; updateUTIL(2*sti+1, sts, mid, ind); updateUTIL(2*sti+2, mid+1, ste, ind); st[sti] = st[2*sti+1] + st[2*sti+2]; } } private int queryUTIL(int sti, int sts, int ste, int qs, int qe) { if (qe<sts || ste<qs) return 0; else if (qs<=sts && ste<=qe) return st[sti]; else { int mid = (sts+ste)/2; return queryUTIL(2*sti+1, sts, mid, qs, qe) + queryUTIL(2*sti+2, mid+1, ste, qs, qe); } } protected int query(int qs, int qe) { return queryUTIL(0, 0, n-1, qs, qe); } } public static void main(String[] args) throws IOException { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); n = in.nextInt(); HashMap<Integer, Integer> hm = new HashMap<>(); int[] arr = new int[n]; int left[] = new int[n]; int[] right = new int[n]; for (int i=0; i<n; i++) arr[i] = in.nextInt(); for (int i=0; i<n; i++) { hm.compute(arr[i], (k, v) -> v == null ? 1:v+1); left[i] = hm.get(arr[i]); } hm.clear(); for (int i=n-1; i>=0; i--) { hm.compute(arr[i], (k, v) -> v == null ? 1:v+1); right[i] = hm.get(arr[i]); } SegmentTree tree = new SegmentTree(); long ans = 0; for (int i=n-1; i>0; i--) { tree.update(right[i]); ans += tree.query(0, left[i-1]-1); } out.printf("%d\n", ans); out.close(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
277e2ca3a0704aa613670e8e8c528203
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import static java.lang.Math.*; public class Main { static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } static int n; static class SegmentTree { private int[] st; protected SegmentTree() { int x = (int)(ceil(log(n) / log(2))); st = new int[(1<<(x+1)) - 1]; } protected void update(int ind) { updateUTIL(0, 0, n-1, ind); } private void updateUTIL(int sti, int sts, int ste, int ind) { if (ind<sts || ind>ste) return; else if (sts == ste) st[sti]++; else { int mid = (sts+ste)/2; updateUTIL(2*sti+1, sts, mid, ind); updateUTIL(2*sti+2, mid+1, ste, ind); st[sti] = st[2*sti+1] + st[2*sti+2]; } } private int queryUTIL(int sti, int sts, int ste, int qs, int qe) { if (qe<sts || ste<qs) return 0; else if (qs<=sts && ste<=qe) return st[sti]; else { int mid = (sts+ste)/2; return queryUTIL(2*sti+1, sts, mid, qs, qe) + queryUTIL(2*sti+2, mid+1, ste, qs, qe); } } protected int query(int qs, int qe) { return queryUTIL(0, 0, n-1, qs, qe); } } public static void main(String[] args) throws IOException { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); n = in.nextInt(); HashMap<Integer, Integer> hm = new HashMap<>(); int[] arr = new int[n]; int left[] = new int[n]; int[] right = new int[n]; for (int i=0; i<n; i++) arr[i] = in.nextInt(); for (int i=0; i<n; i++) { hm.compute(arr[i], (k, v) -> v == null ? 1:v+1); left[i] = hm.get(arr[i]); } hm.clear(); for (int i=n-1; i>=0; i--) { hm.compute(arr[i], (k, v) -> v == null ? 1:v+1); right[i] = hm.get(arr[i]); } SegmentTree tree = new SegmentTree(); long ans = 0; for (int i=n-1; i>0; i--) { tree.update(right[i]); ans += tree.query(0, left[i-1]-1); } out.printf("%d\n", ans); out.close(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
239ec9760501ca08b26d1171a424a22e
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
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.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.util.TreeSet; public class Solution1 implements Runnable { static final long MAX = 464897L; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution1(),"Solution",1<<26).start(); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } long MOD = 1000000007; TreeSet<Pair> adj[]; ArrayList<Pair> adj2[]; public void run() { //InputReader sc= new InputReader(new FileInputStream("input.txt")); //PrintWriter w= new PrintWriter(new FileWriter("output.txt")); InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); long[] arr = new long[n]; for(int i = 0;i < n;i++) { arr[i] = sc.nextLong(); } Map<Long,Integer> tmap = new HashMap(); long[] prefix= new long[n]; TreeSet<Long> tset = new TreeSet(); for(int i = 0;i < n;i++) { if(!tmap.containsKey(arr[i])) { tmap.put(arr[i],1); }else { tmap.put(arr[i],tmap.get(arr[i]) + 1); } prefix[i] = tmap.get(arr[i]); tset.add(prefix[i]); } tmap.clear(); suffix= new long[n]; for(int i = n-1;i >= 0;i--) { if(!tmap.containsKey(arr[i])) { tmap.put(arr[i],1); }else { tmap.put(arr[i],tmap.get(arr[i]) + 1); } suffix[i] = tmap.get(arr[i]); tset.add(suffix[i]); } tmap.clear(); for(Long val: tset) { tmap.put(val,tmap.size() + 1); } segTree = new long[8 * 1000005]; long count = 0; for(int i = n-1;i > 0;i--) { int ind = tmap.get(suffix[i]); int ind2 = tmap.get(prefix[i-1]); update(0, n-1, 0, ind, 1); count += query(0, n-1, 0, 0, ind2-1); } w.println(count); w.close(); } long[] suffix; long[] segTree; void update(int l,int r,int pos,int ind,int val) { if(ind < l || ind > r) { return; } if(l == r) { segTree[pos] += val; return; } int mid = (l + r)/2; update(l, mid, 2*pos+1, ind, val); update(mid+1, r, 2*pos+2, ind, val); segTree[pos] = segTree[2*pos+1] + segTree[2*pos+2]; } long query(int l,int r,int pos,int start,int end) { if(l > r || l > end || r < start) { return 0; } if(l >= start && r <= end) { return segTree[pos]; } int mid = (l + r)/2; long p1 = query(l, mid, 2*pos+1, start, end); long p2 = query(mid+1, r, 2*pos+2, start, end); return (p1 + p2); } class Node implements Comparable<Node>{ int a; int b; long c; Node(int a,int b,long c){ this.a = a; this.b = b; this.c = c; } public boolean equals(Object o) { Node p = (Node)o; return this.a == p.a && this.b == p.b && this.c == p.c; } public int compareTo(Node n) { if(n.c == this.c) { if(n.a == this.a) { return Integer.compare(this.b,n.b); } return Integer.compare(this.a,n.a); } return Long.compare(this.c,n.c); } public int hashCode(){ return Long.hashCode(a)*27 + Long.hashCode(b)* 31 + Long.hashCode(c) * 3; } } class Pair implements Comparable<Pair>{ long a; int b; //int c; Pair(long a,int b){ this.b = b; this.a = a; } public boolean equals(Object o) { Pair p = (Pair)o; return this.a == p.a && this.b == p.b; } public int hashCode(){ return Long.hashCode(a)*27 + Long.hashCode(b)* 31; } public int compareTo(Pair p) { return Long.compare(this.a,p.a); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
7ced6187dba85a975e4856fc5f583efa
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class C459D { public static void main(String[] args) { IntIO459D sc = new IntIO459D(System.in); 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]; int r[] = new int[n]; int m = 1000005; Map<Integer, Integer> map = new HashMap(); for (int i = 0; i < n; i++) { Integer vl = map.get(a[i]); if (vl!=null) vl++; else vl = 1; map.put(a[i], vl); l[i] = vl; } for (int i = 0; i < n; i++) { r[i] = map.get(a[i]) - l[i] + 1; } SegmentTree459D st = new SegmentTree459D(m); long ans = 0; for (int i = n - 1; i >= 1; i--) { st.Add(r[i], r[i] + 1, 1); ans += st.Sum(1, l[i - 1]); } System.out.println(ans); } } class Node459D { long value = 0; long lazy = 0; } class SegmentTree459D { int n; Node459D data[]; public SegmentTree459D(int n_) { n = 1; while (n < n_) n *= 2; data = new Node459D[2 * n - 1]; for (int i = 0; i < 2 * n - 1; i++) { data[i] = new Node459D(); } } void Add(int a, int b, long x) { add(a, b, 0, 0, n, x); } private void add(int a, int b, int k, int l, int r, long x) { if (r <= a || b <= l) return; if (a <= l && r <= b) { data[k].lazy += x; return; } data[k].value += (Math.min(b, r) - Math.max(a, l)) * x; add(a, b, k * 2 + 1, l, (l + r) / 2, x); add(a, b, k * 2 + 2, (l + r) / 2, r, x); } long Sum(int a, int b) { return sum(a, b, 0, 0, n); } private long sum(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return 0; // khong thuoc doan truy van thi tra ve 0 if (a <= l && r <= b) return (r - l) * data[k].lazy + data[k].value; long vl = sum(a, b, k * 2 + 1, l, (l + r) / 2); long vr = sum(a, b, k * 2 + 2, (l + r) / 2, r); return vl + vr + (Math.min(b, r) - Math.max(a, l)) * data[k].lazy; // sum } } class IntIO459D extends BufferedInputStream { public IntIO459D(final InputStream in) { super(in); } public IntIO459D(final InputStream in, final int buf_size) { super(in, buf_size); } public int nextInt() { try { int chr = read(); while (chr <= ' ') chr = read(); int sum = chr - '0'; while ((chr = read()) > ' ') sum = (sum << 3) + sum + sum + chr - '0'; return sum; } catch (Exception e) { } return 0; } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
5a9344988adde097ff0c1965c151e994
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class gym { static class FenwickTree { int[] ft; FenwickTree(int n) { ft = new int[n + 1]; } void update(int idx, int val) { while(idx < ft.length) { ft[idx] += val; idx += idx & -idx; } } int query(int idx) { int s = 0; while(idx > 0) { s += ft[idx]; idx ^= idx & -idx; } return s; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); int a[] = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(st.nextToken()); } FenwickTree ft = new FenwickTree(n); HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = n - 1; i >= 0; i--) { Integer x = hm.get(a[i]); if (x == null) x = 0; x++; hm.put(a[i], x); ft.update(x, 1); } long ans = 0; HashMap<Integer, Integer> hm2 = new HashMap<>(); for (int i = 0; i < a.length; i++) { hm2.put(a[i], hm2.getOrDefault(a[i], 0) + 1); int x = hm2.get(a[i]); int z = hm.get(a[i]); ft.update(z, -1); hm.put(a[i], z - 1); ans += ft.query(x - 1); } pw.print(ans); pw.flush(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
9659038431937ee9d514e124c41ebbdf
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static int n; static int [] BIT; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; n = parseInt(in.readLine()); int [] a = new int[n+1]; tk = new StringTokenizer(in.readLine()); for(int i=1; i<=n; i++) a[i] = parseInt(tk.nextToken()); BIT = new int[n+1]; int [] fl = new int[n+1]; int [] fr = new int[n+1]; Map<Integer,Integer> m = new HashMap<>(); for(int i=1; i<=n; i++) { if(!m.containsKey(a[i])) m.put(a[i], 0); fl[i] = m.get(a[i])+1; m.put(a[i], fl[i]); } m.clear(); for(int i=n; i>=1; i--) { if(!m.containsKey(a[i])) m.put(a[i], 0); fr[i] = m.get(a[i])+1; m.put(a[i], fr[i]); } /* for(int i=0; i<n; i++) System.out.print(fl[i]+" "); System.out.println(""); for(int i=0; i<n; i++) System.out.print(fr[i]+" "); System.out.println(""); */ long ans = 0; for(int i=n; i>=1; i--) { ans += get(fl[i]-1); add(fr[i]); } System.out.println(ans); } static void add(int i) { while(i <= n) { BIT[i]++; i += (i & -i); } } static long get(int i) { long ans = 0; while(i > 0) { ans += BIT[i]; i -= (i & -i); } return ans; } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
9166fa2b5275951855986fccf9d219d1
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashMap; public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { solve(); } }, "1", 1 << 26).start(); } static void solve () { FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out); int n =fr.nextInt() ,a[] =new int[n] ,frnt[] =new int[n] ,bck[] =new int[n] ,i ; long bit[] =new long[n+1] ,ans =0l ; for (i =0 ; i<n ; ++i) a[i] =fr.nextInt() ; HashMap<Integer,Integer> ct =new HashMap<>() ; for (i =0 ; i<n ; ++i) { if (!ct.containsKey(a[i])) ct.put(a[i],0) ; ct.put(a[i],ct.get(a[i])+1) ; frnt[i] =ct.get(a[i]) ; } ct.clear() ; for (i =n-1 ; i>-1 ; --i) { if (!ct.containsKey(a[i])) ct.put(a[i],0) ; ct.put(a[i],ct.get(a[i])+1) ; bck[i] =ct.get(a[i]) ; } for (i =n-1 ; i>-1 ; --i) upd (bit , bck[i] , 1l) ; for (i =0 ; i<n ; ++i) { upd (bit , bck[i] , -1) ; ans += query (bit , frnt[i]-1) ; } op.println(ans) ; op.flush(); op.close(); } static void upd (long bit[] , int pos , long v) { for (int i =pos ; i<bit.length ; i += (i&(-i))) bit[i] += v ; } static long query (long bit[] , int pos) { long r =0l ; for (int i =pos ; i>0 ; i -= (i&(-i))) r += bit[i] ; return r; } 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(); } String nextLine() { String str =""; try { str =br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()) ; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
7d41c689f9b390f4ad5286cc20d16f9a
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class D459 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int [] arr = new int [n]; for (int i = 0; i < arr.length; i++) { arr[i]=sc.nextInt(); } HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>(); int [] a = new int [n]; int [] b = new int [n]; FenwickTree ft = new FenwickTree(n+3); for(int i=0;i<n;i++) { if(hm.containsKey(arr[i])) { a[i]=hm.get(arr[i])+1; hm.put(arr[i], a[i]); }else { hm.put(arr[i], 1); a[i]=1; } ft.point_update(a[i], 1); } hm= new HashMap<Integer, Integer>(); long ans =0; for(int i=n-1;i>=0;i--) { if(hm.containsKey(arr[i])) { b[i]=hm.get(arr[i])+1; hm.put(arr[i], b[i]); }else { hm.put(arr[i], 1); b[i]=1; } ft.point_update(a[i], -1); ans +=ft.rsq(b[i]+1,n); } pw.println(ans); pw.close(); pw.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 > 0) { 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 <= n) { ft[k] += val; k += k & -k; } //min? } int point_query(int idx) // c * O(log n), c < 1 { int sum = ft[idx]; if(idx > 0) { int z = idx ^ (idx & -idx); --idx; while(idx != z) { sum -= ft[idx]; idx ^= idx & -idx; } } return sum; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
85058902d79b1416abf46cc5a26a0ac1
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeSet; /** * @author Don Li */ public class PashmakParmidaProblem2 { static final int MAXN = (int) (1e6 + 5); int n; int[] bit; void solve() { n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); compress(a); bit = new int[n + 2]; int[] tot = new int[MAXN]; for (int i = n - 1; i >= 0; i--) { update(++tot[a[i]], 1); } long ans = 0; int[] cur = new int[MAXN]; for (int i = 0; i < n; i++) { int cnt = tot[a[i]] - cur[a[i]]++; update(cnt, -1); ans += query(0, cur[a[i]] - 1); } out.println(ans); } void compress(int[] a) { TreeSet<Integer> set = new TreeSet<>(); for (int x : a) set.add(x); int id = 0; Map<Integer, Integer> map = new HashMap<>(); for (int x : set) map.put(x, id++); for (int i = 0; i < a.length; i++) { a[i] = map.get(a[i]); } } void update(int i, int x) { i++; while (i <= n + 1) { bit[i] += x; i += i & -i; } } int query(int i) { i++; int sum = 0; while (i > 0) { sum += bit[i]; i -= i & -i; } return sum; } int query(int a, int b) { return query(b) - query(a); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new PashmakParmidaProblem2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
c32b1c94824bcc1bf65ceae7730cae25
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author Don Li */ public class PashmakParmidaProblem { void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Map<Integer, Integer> tot_cnt = new HashMap<>(); for (int i = 0; i < n; i++) { tot_cnt.put(a[i], tot_cnt.getOrDefault(a[i], 0) + 1); } FenwickTree st = new FenwickTree(n + 1); for (int k : tot_cnt.keySet()) { int v = tot_cnt.get(k); st.update(v, 1); } long ans = 0; Map<Integer, Integer> cur_cnt = new HashMap<>(); for (int i = 0; i < n; i++) { cur_cnt.put(a[i], cur_cnt.getOrDefault(a[i], 0) + 1); int x = cur_cnt.get(a[i]); int freq = tot_cnt.get(a[i]); st.update(freq, -1); st.update(freq - 1, 1); tot_cnt.put(a[i], freq - 1); int tot = n - i - 1; int[] ret = st.query(x - 1, n); int sum = ret[0], cnt = ret[1]; ans += tot - (sum - cnt * (x - 1)); } out.println(ans); } static class FenwickTree { int n; int[] cnt, sum; FenwickTree(int n) { this.n = n; cnt = new int[n + 1]; sum = new int[n + 1]; } void update(int i, int x) { int y = i * x; i++; while (i <= n) { cnt[i] += x; sum[i] += y; i += i & -i; } } int[] query(int i) { int[] res = new int[2]; i++; while (i > 0) { res[0] += sum[i]; res[1] += cnt[i]; i -= i & -i; } return res; } int[] query(int a, int b) { int[] x = query(a), y = query(b); return new int[]{y[0] - x[0], y[1] - x[1]}; } } static class SegmentTree { int n; int[] cnt, sum; SegmentTree(int m) { int x = 0; while ((1 << x) < m) x++; n = 1 << x; cnt = new int[2 * n - 1]; sum = new int[2 * n - 1]; } void update(int i, int x) { int t = i; i += n - 1; cnt[i] += x; sum[i] += x * t; while (i > 0) { i = (i - 1) / 2; cnt[i] += x; sum[i] += x * t; } } int[] query(int a, int b) { return query(a, b, 0, 0, n); } int[] query(int a, int b, int k, int l, int r) { if (a >= r || b <= l) return new int[]{0, 0}; if (a <= l && r <= b) return new int[]{sum[k], cnt[k]}; int[] x = query(a, b, 2 * k + 1, l, (l + r) / 2); int[] y = query(a, b, 2 * k + 2, (l + r) / 2, r); return new int[]{x[0] + y[0], x[1] + y[1]}; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new PashmakParmidaProblem().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
83f62526d119d6caa308f1c0baabe135
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class C { static int mod = 1000000007; public static void main(String[] args) { Scanner nik = new Scanner(System.in); int n = nik.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nik.nextInt(); } HashMap<Integer, Integer> ht = new HashMap<>(); int[] s = new int[n]; for (int i = 0; i < n; i++) { ht.put(a[i], ht.getOrDefault(a[i], 0) + 1); s[i] = ht.get(a[i]); } ht = new HashMap<>(); int[] u = new int[n]; for (int i = n - 1; i >= 0; i--) { ht.put(a[i], ht.getOrDefault(a[i], 0) + 1); u[i] = ht.get(a[i]); } long res = 0; long[] ft = new long[n]; for (int i = n - 1; i >= 0; i--) { res += (query(s[i] - 1, ft)); update(u[i], ft); } System.out.println(res); } private static long query(int e, long[] ft) { long res = 0; while (e > 0) { res += ft[e]; e -= (e & -e); } return res; } private static void update(int u, long[] ft) { while (u < ft.length) { ft[u]++; u += (u & -u); } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
e33e0a159381388d909c3ac8fac2b572
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; public class P { static class BIT { int n; int[] ft; BIT(int size) { n = size; ft = new int[n + 1]; } int query(int b) { int sum = 0; while (b > 0) { sum += ft[b]; b -= b & -b; } return sum; } void add(int k, int val) { while (k <= n) { ft[k] += val; k += k & -k; } } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] a = sc.nextIntArray(N); BIT ft = new BIT(N); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); long answer = 0; int[] idxOf = new int[N]; for (int i = N - 1; i >= 0; --i) { Integer occ = map.get(a[i]); if (occ == null) occ = 0; map.put(a[i], occ + 1); idxOf[i] = occ + 1; ft.add(occ + 1, 1); } map.clear(); for (int i = 0; i < N; ++i) { Integer occ = map.get(a[i]); if (occ == null) occ = 0; map.put(a[i], occ + 1); ft.add(idxOf[i], -1); answer += ft.query(occ); } System.out.println(answer); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
4a0bed8a039f2e9ce4ef5e95214a86c6
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class D { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); class BIT { //one-indexed int[] tree; public BIT(int size) { tree = new int[size+10]; } public void upd(int k, int x) { ++k; while(k < tree.length) { tree[k] += x; k += (k&-k); } } public int query(int l, int r) { return sum(r) - sum(l-1); } public int ele(int ind) { return sum(ind) - sum(ind-1); } public int sum(int q) { ++q; int res = 0; while(q >= 1) { res += tree[q]; q -= (q&-q); } return res; } } public void run() throws Exception { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int[] a = new int[n]; int[] f = new int[n]; int[] s = new int[n]; for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); if(!m.containsKey(a[i])) { m.put(a[i], 0); } m.put(a[i], m.get(a[i])+1); f[i] = m.get(a[i]); } m.clear(); for(int i = n-1; i >= 0; i--) { if(!m.containsKey(a[i])) { m.put(a[i], 0); } m.put(a[i], m.get(a[i])+1); s[i] = m.get(a[i]); } BIT b = new BIT(n); b.upd(f[0], 1); long ans = 0; for(int i = 1; i < n; i++) { ans += b.query(s[i]+1, n); b.upd(f[i], 1); } System.out.println(ans); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } public static void main(String[] args) throws Exception { new D().run(); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
21afa755a73f8bf43d872488c44f19ad
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
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.StringTokenizer; import java.util.TreeMap; public class A { static int n; static int [] BIT; public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out,true); n=sc.nextInt(); BIT=new int [n+1]; int [] a=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); HashMap<Integer, Integer> map=new HashMap<Integer, Integer>(); int [] f1=new int [n],fn=new int [n]; for(int i=0;i<n;i++){ if(map.containsKey(a[i])) map.put(a[i], map.get(a[i])+1); else map.put(a[i], 1); f1[i]=map.get(a[i]); } map.clear(); for(int i=n-1;i>=0;i--){ if(map.containsKey(a[i])) map.put(a[i], map.get(a[i])+1); else map.put(a[i], 1); fn[i]=map.get(a[i]); } long ans=0; for(int i=0;i<n;i++){ ans+=get(n)-get(fn[i]); add(f1[i], 1); } pw.println(ans); pw.flush(); pw.close(); } public static void add(int idx,int val){ while(idx>0 && idx<=n){ BIT[idx]+=val; idx+=(idx & -idx); } } public static int get(int idx){ int ans=0; while(idx>0){ ans+=BIT[idx]; idx-=(idx & -idx); } return ans; } 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
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
e14d30928743076bf3f40ee8ca89f58e
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new PrintStream(System.out)); int n=Integer.parseInt(f.readLine()); pair[]arr=new pair[n]; pair[]cnt=new pair[n]; StringTokenizer st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ arr[i]=new pair(Integer.parseInt(st.nextToken()),i); cnt[i]=new pair(arr[i]); } Arrays.sort(cnt); int[]freq=new int[n]; int[]freq2=new int[n]; pair[]cnto=new pair[n]; pair[]cnto2=new pair[n]; for(int i=0;i<n;i++){ arr[i].num=lowerBound(cnt,n,arr[i].num); } for(int i=0;i<n;i++){ freq[arr[i].num]++; freq2[arr[n-1-i].num]++; cnto[i]=new pair(freq[arr[i].num],i); cnto2[i]=new pair(freq2[arr[n-1-i].num],i); } int[]freq3=new int[n+5]; long ans=0; // Arrays.sort(cnto); // Arrays.sort(cnto2); for(int i=n-1;i>=0;i--){ ans+=query(cnto[i].num)-freq3[cnto[i].num]; update(cnto2[n-1-i].num,1,n+5); freq3[cnto2[n-1-i].num]++; } System.out.println(ans); f.close(); out.close(); } public static int lowerBound(pair[] array, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value <= array[mid].num) { high = mid; } else { low = mid + 1; } } return low; } static long[]BIT=new long[1000100]; //add val at index x static void update(int x, long val,int n) { x++; for(; x <= n; x += x&-x) BIT[x] += val; } static long query(int x) { x++; long sum = 0; for(; x > 0; x -= x&-x) sum += BIT[x]; return sum; } } class pair implements Comparable <pair>{ int num; int idx; public int compareTo(pair other){ return num- other.num; } pair(int a, int b) { num=a; idx=b; } pair(pair a){ num=a.num; idx=a.idx; } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
e9462e625a6a00aa061d32b6001b04f9
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ InputStream is; static PrintWriter out; String INPUT = ""; static long mod = (long)1e9+7L; static class SegmentTree{ static class Node{ int l, r, v; Node left, right; Node(int a, int b, int c){ l = a; r = b; v = c; left = null; right = null; } public String toString(){ return "("+l+","+r+","+v+")"; } } Node root; int size; int[] data; SegmentTree(int s, int[] d){ // size is the size of array d on which ST is going to build. this.size = s; data = d; root = build(0, size-1); } Node build(int a, int b){ // function to initialize the ST. Node node = new Node(a, b, 0); if(a == b){ node.v = data[a]; return node; // stop when reach to leaf node } int mid = (a+b)/2; node.left = build(a, mid); // build the left child node.right = build(mid+1, b); // build the rigth child node.v = merge(node.left, node.right).v; // put the value of merged child nodes System.out.println(node); return node; } Node merge(Node n1, Node n2){// function to merge left child and right child respectively. n1 and n2 are passed by reference so don't change the object. return new Node(n1.l, n2.r, n1.v+n2.v); // change this function accordingly. } void pointUpdate(int idx, int v){ data[idx] = v; System.out.println(root); pointUpdateUtils(root, idx, v); } Node pointUpdateUtils(Node root, int idx, int key){ if(root.l > idx || root.r < idx)return root; if(root.l == root.r){ root.v = key; return root; } Node c1 = pointUpdateUtils(root.left, idx, key); Node c2 = pointUpdateUtils(root.right, idx, key); root.v = merge(c1, c2).v; return root; } int query(int l, int r){ if(l > r)return 0; return queryUtils(root, l, r).v; } Node queryUtils(Node root, int a, int b){ if(root.l > b || root.r < a)return new Node(0, 0, 0); if(root.l <= a && root.r >= b)return root; Node c1 = queryUtils(root.left, a, b); Node c2 = queryUtils(root.right, a, b); return merge(c1, c2); } } public void solve(){ int n = ni(); int[] a = na(n); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] d = new int[n+1]; for(int i = n-1; i >= 0; i--){ if(map.containsKey(a[i])){ map.put(a[i], map.get(a[i])+1); d[map.get(a[i])] += 1; } else{ map.put(a[i], 1); d[1] += 1; } } //out.println(Arrays.toString(d)); int[] bit = new int[n+1]; bit[1] = d[1]; for(int i = 2; i < n+1; i++){ d[i] += d[i-1]; int cr = i&((-1)*i); bit[i] = d[i] - d[i-cr]; } //out.println(Arrays.toString(bit)); HashMap<Integer, Integer> map1 = new HashMap<Integer, Integer>(); long ans = 0L; for(int i = 0; i < n; i++){ //System.out.println(a[i]); map1.put(a[i], map1.containsKey(a[i]) ? map1.get(a[i])+1 : 1); update(bit, map.get(a[i])); map.put(a[i], map.get(a[i])-1); ans = ans + query(bit, map1.get(a[i])-1); } out.println(ans); } void update(int[] bit, int idx){ int n = bit.length; while(idx < n){ bit[idx] -= 1; //out.println(idx); idx += (idx&((-1)*idx)); } } long query(int[] bit, int idx){ long ret = 0L; while(idx > 0){ ret += (long)bit[idx]; idx -= (idx & ((-1)*idx)); } return ret; } void run(){ is = new DataInputStream(System.in); out = new PrintWriter(System.out); int t=1;while(t-->0)solve(); out.flush(); } public static void main(String[] args)throws Exception{new Solution().run();} long mod(long v, long m){if(v<0){long q=(Math.abs(v)+m-1L)/m;v=v+q*m;}return v%m;} long mod(long v){if(v<0){long q=(Math.abs(v)+mod-1L)/mod;v=v+q*mod;}return v%mod;} //Fast I/O code is copied from uwi code. private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private 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 boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(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 char[][] nm(int n, int m){ char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n){ int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni(){ 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 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 int i(long x){return (int)Math.round(x);} static class Pair implements Comparable<Pair>{ long fs,sc; Pair(long a,long b){ fs=a;sc=b; } public int compareTo(Pair p){ if(this.fs>p.fs)return 1; else if(this.fs<p.fs)return -1; else{ return i(this.sc-p.sc); } //return i(this.sc-p.sc); } public String toString(){ return "("+fs+","+sc+")"; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
a7632c40eaafba6790039d5ba01923f9
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Miras */ import java.util.Scanner; import java.util.TreeMap; import java.util.Arrays; public class solve { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; int[] s = new int[n]; FenwickTree fw = new FenwickTree(n + 1); for (int i = 0; i < n; ++i) a[i] = sc.nextInt(); a = compress(a); int[] cnt = new int[n + 1]; for (int i = 0; i < n; ++i) { cnt[a[i]]++; s[i] = cnt[a[i]]; fw.upd(cnt[a[i]], 1); } for (int i = 0; i <= n; ++i) cnt[i] = 0; long ans = 0; for (int i = n - 1; i > 0; --i) { fw.upd(s[i], -1); int x = ++cnt[a[i]]; ans += fw.getSum(x + 1, n); } System.out.println(ans); } private static int[] compress(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); int sz = 0; for (int i = 0; i < n; ) { int j = i; while (j < n && b[i].equals(b[j])) j++; b[sz++] = b[i]; i = j; } for (int i = 0; i < n; ++i) a[i] = Arrays.binarySearch(b, 0, sz, a[i]); return a; } } class FenwickTree { int size; int[] f; public FenwickTree (int x) { size = x; f = new int[size]; } void upd(int x, int delta) { for (int i = x; i < size; i = (i | (i + 1))) { f[i] += delta; } } int sum(int r) { int res = 0; for (int i = r; i >= 0; i = (i & (i + 1)) - 1) { res += f[i]; } return res; } int getSum(int l, int r) { return sum(r) - sum(l - 1); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
35641b2b6b6b72a82fa0e1f4b7bc504f
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import sun.reflect.generics.tree.Tree; import java.io.*; import java.math.*; import java.util.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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 String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(), "Main", 1 << 26).start(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long modPow(long a, long p, long m) { if (a == 1) return 1; long ans = 1; while (p > 0) { if (p % 2 == 1) ans = (ans * a) % m; a = (a * a) % m; p >>= 1; } return ans; } static long modInv(long a, long m) { return modPow(a, m - 2, m); } static long sol_x, sol_y, gcd_a_b; static void extendedEuclid(long a, long b) { if (b == 0) { gcd_a_b = a; sol_x = 1; sol_y = 0; } else { extendedEuclid(b, a % b); long temp = sol_x; sol_x = sol_y; sol_y = temp - (a / b) * sol_y; } } long modInverse(long a, long prime) { a = a % prime; for (int x=1; x<prime; x++) if ((a*x) % prime == 1) return x; return -1; } static class Bhavansort { Random random; Bhavansort(int a[]) { randomArray(a); sort(a); } Bhavansort(long a[]) { randomArray(a); sort(a); } static int[] sort(int a[]) { Arrays.sort(a); return a; } static long[] sort(long a[]) { Arrays.sort(a); return a; } void randomArray(long a[]) { int n = a.length; for (int i = 0; i < n; i++) { int p = random.nextInt(n) % n; long tm = a[i]; a[i] = a[p]; a[p] = tm; } } void randomArray(int a[]) { int n = a.length; for (int i = 0; i < n; i++) { int p = random.nextInt(n) % n; int tm = a[i]; a[i] = a[p]; a[p] = tm; } } } public void run() { InputReader sc = new InputReader(System.in); //Scanner sc=new Scanner(System.in); // Random rn=new Random(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int a[][]=new int[n][2]; for (int i = 0; i <n ; i++) { a[i][0]=sc.nextInt(); a[i][1]=i; } HashMap<Integer,Integer> map=new HashMap<>(); int pre[]=new int[n]; int suf[]=new int[n]; for (int i = 0; i <n ; i++) { if(map.containsKey(a[i][0])){ map.put(a[i][0],map.get(a[i][0])+1); } else{ map.put(a[i][0],1); } pre[i]=map.get(a[i][0]); } map=new HashMap<>(); for (int i = n-1; i >=0 ; i--) { if(map.containsKey(a[i][0])){ map.put(a[i][0],map.get(a[i][0])+1); } else{ map.put(a[i][0],1); } suf[i]=map.get(a[i][0]); } FenwickTree ft=new FenwickTree(n); ft.update(suf[n-1],1); long ans=0; for (int i = n-2; i >=0 ; i--) { ans+=ft.query(pre[i]-1); ft.update(suf[i],1); } out.println(ans); out.close(); } class FenwickTree { int[] ft; FenwickTree(int n) { ft = new int[n + 1]; } void update(int idx, int val) { while(idx < ft.length) { ft[idx] += val; idx += idx & -idx; } } int query(int idx) { int s = 0; while(idx > 0) { s += ft[idx]; idx ^= idx & -idx; } return s; } } class Node{ int val,c; public Node(int val, int c) { this.val = val; this.c = c; } } class ST{ SegNode tree[]; public ST(int n){ tree=new SegNode[2*n]; } SegNode opration(SegNode o1,SegNode o2){ return new SegNode(o1.val+o2.val); } void build(int cur,int l,int r,int a[]){ if(l==r){ tree[cur].val=a[l]; return; } int mid=(l+r)>>1; build(2*cur+1,l,mid,a); build(cur*2+2,mid+1,r,a); tree[cur]=opration(tree[(cur<<1)+1],tree[(cur<<1)+2]); } void update(int cur,int l,int r,int changeIndex,int changeValue){ if(l==r){ tree[cur].val+=changeValue; return; } int mid=(l+r)>>1; if(mid>=changeIndex) { update(2 * cur + 1, l, mid, changeIndex,changeValue); } else { update(2 * mid + 2, mid + 1, r, changeIndex,changeValue); } tree[cur]=opration(tree[(cur<<1)+1],tree[(cur<<1)+2]); } SegNode query(int cur,int l,int r,int qstart,int qend){ if(qstart>=l && r<=qend){ return tree[cur]; } int mid=(l+r)>>1; SegNode default1=null,default2=null; default1=query(2*cur+1,l,mid,qstart,qend); default2=query(2*cur+1,mid+1,r,qstart,qend); return opration(default1,default2); } class SegNode{ int val; public SegNode(int val) { this.val = val; } } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
51dfdc87197066452f8cf4c6c26ddef8
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.TreeMap; public class Main1 { static PrintWriter out = new PrintWriter(System.out); static Reader input = new Reader(); static final int MAXN = (int) 1e6; static int st[], lazy[]; static void upadte(int i, int l, int r, int x, int y, int v) { if (l > y || r < x) return; else if (l >= x && r <= y) { st[i] += v; } else { upadte(i << 1, l, r + l >> 1, x, y, v); upadte((i << 1) + 1, (l + r >> 1) + 1, r, x, y, v); st[i] = st[i << 1] + st[(i << 1) + 1]; } } static int query(int i, int l, int r, int x, int y) { if (l > y || r < x) return 0; else if (l >= x && r <= y) { return st[i]; } else { return query(i << 1, l, r + l >> 1, x, y) + query((i << 1) + 1, (l + r >> 1) + 1, r, x, y); } } public static void main(String[] args) throws IOException { int n = input.nextInt(); int a[] = new int[n]; TreeMap<Integer, Integer> p = new TreeMap<>(); TreeMap<Integer, Integer> s = new TreeMap<>(); for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } int prefix[] = new int[n]; int suffix[] = new int[n]; st = new int[n << 2]; lazy = new int[n << 2]; for (int i = 0; i < n; i++) { Integer x = p.get(a[i]); x = x == null ? 0 : x; Integer y = s.get(a[n - i - 1]); y = y == null ? 0 : y; prefix[i] = x + 1; suffix[n - i - 1] = y + 1; p.put(a[i], prefix[i]); s.put(a[n - i - 1], suffix[n - i - 1]); } long sum = 0; for (int i = n - 2; i >= 0; i--) { upadte(1, 0, n - 1, suffix[i + 1], suffix[i + 1], 1); int cur = query(1, 0, n - 1, 1, prefix[i] - 1); sum += cur; } out.println(sum); out.flush(); } 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[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; 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 class con { static int IINF = (int) 1e9; static int _IINF = (int) -1e9; static long LINF = (long) 1e15; static long _LINF = (long) -1e15; static double EPS = 1e-9; } static class Triple implements Comparable<Triple> { int x; int y; int z; Triple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public int compareTo(Triple o) { if (x == o.x && y == o.y) return z - o.z; if (x == o.x) return y - o.y; return x - o.x; } @Override public String toString() { return "(" + x + ", " + y + ", " + z + ")"; } } 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 (x == o.x) return y - o.y; return x - o.x; } @Override public String toString() { return "(" + x + ", " + y + ")"; } } static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int r = i + (int) (Math.random() * (a.length - i)); int tmp = a[r]; a[r] = a[i]; a[i] = tmp; } } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static class DSU { int[] p, rank, setSize; int numSets; DSU(int n) { p = new int[n]; rank = new int[n]; setSize = new int[n]; numSets = n; for (int i = 0; i < n; i++) { p[i] = i; setSize[i] = 1; } } int findSet(int n) { return p[n] = p[n] == n ? n : findSet(p[n]); } boolean isSameSet(int n, int m) { return findSet(n) == findSet(m); } void mergeSet(int n, int m) { if (!isSameSet(n, m)) { numSets--; int p1 = findSet(n); int p2 = findSet(m); if (rank[p1] > rank[p2]) { p[p2] = p1; setSize[p1] += setSize[p2]; } else { p[p1] = p2; setSize[p2] += setSize[p1]; if (rank[p1] == rank[p2]) rank[p1]++; } } } int size() { return numSets; } int setSize(int n) { return setSize[findSet(n)]; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
5da5cf2340bb3d997e70a964523f4e20
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
import java.io.*; import java.util.*; /** * Created by vikas.k on 25/12/16. */ public class CF261D { public static void main(String[] args){ CF261D gv = new CF261D(); gv.solve(); } private int[] rgt; private int[] fnk; int n; private void solve(){ MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); n = sc.nextInt(); List<Integer> str = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); for(int i=0;i<n;i++){ str.add(sc.nextInt()); tmp.add(str.get(i)); } Collections.sort(tmp); for(int i=0;i<n;i++){ str.set(i,Collections.binarySearch(tmp,str.get(i))); } //out.println(str.toString()); Map<Integer,Integer> cnt = new HashMap<>(); fnk = new int[n+1]; rgt = new int[n+1]; for(int i=n-1;i>=0;i--){ int v = str.get(i); if(!cnt.containsKey(v)) cnt.put(v,0); rgt[i] = cnt.get(v)+1; cnt.put(v,rgt[i]); add(rgt[i],1); } cnt.clear(); long ans =0; for(int i=0;i<n;i++){ int v = str.get(i); if(!cnt.containsKey(v)) cnt.put(v,0); add(rgt[i],-1); cnt.put(v,cnt.get(v)+1); ans+= get(cnt.get(v)); } out.println(ans); out.close(); } private void add(int x,int v){ for(int i = x; i<n+1;i+=i&(-i)) fnk[i]+=v; } private long get(int x){ long ret =0; for(int i = x-1;i>0;i-=i&(-i)) ret+=fnk[i]; return ret; } public static PrintWriter out; private static class MyScanner{ BufferedReader bufferedReader; StringTokenizer stringTokenizer; private MyScanner(){ bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } private String next(){ if(stringTokenizer == null || !stringTokenizer.hasMoreElements()){ try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt(){ return Integer.parseInt(next()); } private String nextLine(){ String ret= ""; try { ret= bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ret; } } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
c2828074a0f800d7348824b52d58168d
train_001.jsonl
1408116600
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i &lt; j ≀ n) such that f(1, i, ai) &gt; f(j, n, aj).Help Pashmak with the test.
256 megabytes
// package SegmentTree; import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeSet; public class PashmakAndParmida { public static int query(int tree[],int s,int e,int q,int node){ if(e<=q){ return tree[node]; } if(s>q){ return 0; } int mid=(s+e)/2; int left=query(tree,s,mid,q,2*node); int right=query(tree,mid+1,e,q,2*node+1); return left+right; } public static void update(int tree[],int s,int e,int ind,int node){ if(s==e){ tree[node]++; return; } int mid=(s+e)/2; if(ind<=mid){ update(tree,s,mid,ind,2*node); } else{ update(tree,mid+1,e,ind,2*node+1); } tree[node]=tree[2*node]+tree[2*node+1]; } public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int n=Integer.parseInt(br.readLine()); HashMap<Integer,Integer> map=new HashMap<>(); st=new StringTokenizer(br.readLine()); TreeSet<Integer> set=new TreeSet<>(); int a[]=new int[n+1]; for(int i=1;i<=n;i++){ a[i]=Integer.parseInt(st.nextToken()); set.add(a[i]); } int count=0; int tree[]=new int[4*n+4]; for(int k:set){ map.put(k,count++); } int freq[]=new int[count]; for(int i=1;i<=n;i++){ a[i]=map.get(a[i]); freq[a[i]]++; } long ans=0; int freqb[]=new int[n+1]; for(int i=n;i>=1;i--){ int t=query(tree,1,n,freq[a[i]]-1,1); // System.out.println(t); ans+=t; freqb[a[i]]++; freq[a[i]]--; update(tree,1,n,freqb[a[i]],1); } System.out.println(ans); } }
Java
["7\n1 2 1 1 2 2 1", "3\n1 1 1", "5\n1 2 3 4 5"]
3 seconds
["8", "1", "0"]
null
Java 8
standard input
[ "data structures", "sortings", "divide and conquer" ]
d3b5b76f0853cff6c69b29e68a853ff7
The first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).
1,800
Print a single integer β€” the answer to the problem.
standard output
PASSED
b1cc521dad35be16d4a417eed3051523
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static boolean debug = false; static void solve() { int n = ir.nextInt(); int[] a = ir.nextIntArray(2 * n); Arrays.sort(a); for (int i = 0; i <= n; i++) { if (a[i] == a[i + n - 1]) { out.println(0); return; } } long mi = (long) (a[n - 1] - a[0]) * (long) (a[2 * n - 1] - a[n]); for (int i = 1; i < n; i++) { mi = Math.min(mi, (long) (a[2 * n - 1] - a[0]) * (long) (a[n - 1 + i] - a[i])); } out.println(mi); } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static void tr(Object... o) { if (debug) out.println(Arrays.deepToString(o)); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
7f1a4eab64a61722884eb16a08c9d868
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
/* package whatever; // 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 { public static void main (String[] args) throws java.lang.Exception { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(f.readLine()); long[] a = new long[2*n]; StringTokenizer st = new StringTokenizer(f.readLine()); for(int i = 0; i < 2*n; i ++){ a[i] = Long.parseLong(st.nextToken()); } Arrays.sort(a); long min1 = Integer.MAX_VALUE; long max1 = 0; for(int i = 0; i < n ; i++){ min1 = Math.min(min1,a[i]); max1 = Math.max(max1,a[i]); } long min2 = Integer.MAX_VALUE; long max2 = 0; for(int i = 0; i < n ; i++){ min2 = Math.min(min2,a[i+n]); max2 = Math.max(max2,a[i+n]); } long ans = (max1 - min1) * (max2 - min2); for(int i = 1; i < n; i ++){ ans = Math.min(ans,(a[i+n-1] - a[i])*(a[2*n-1]-a[0])); } System.out.println(ans); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
0bc2bc604d3a1f10f499b98516c2b498
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
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.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.stream.Stream; public class Solution implements Runnable { static final double time = 1e9; static final int MOD = (int) 1e9 + 7; static final long mh = Long.MAX_VALUE; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Solution(), "persefone", 1 << 28).start(); } @Override public void run() { long start = System.nanoTime(); solve(); printf(); long elapsed = System.nanoTime() - start; // out.println("stamp : " + elapsed / time); // out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS)); close(); } void solve() { int n = in.nextInt(); long[] a = new long[n << 1]; for (int i = 0; i < n << 1; i++) a[i] = in.nextLong(); Arrays.sort(a); long min = (a[n - 1] - a[0]) * (a[2 * n - 1] - a[n]); for (int i = n; i < n << 1; i++) { min = Math.min((a[i] - a[i - n + 1]) * (a[2 * n - 1] - a[0]), min); } printf(min); } public interface Hash { public void computeHashArray(); public void computeModArray(); } class StringHash implements Hash { // length of string s private final long MH = Long.MAX_VALUE; private int n; private char[] ch; private long[] hash, mod; StringHash(char[] ch) { this.ch = ch; n = ch.length; hash = new long[n + 1]; mod = new long[n + 1]; computeHashArray(); computeModArray(); } StringHash(String s) { this(s.toCharArray()); } StringHash(CharSequence s) { this(s.toString()); } @Override public void computeModArray() { mod[0] = 1; for (int i = 1; i <= n; i++) mod[i] = (mod[i - 1] * 53) % MH; } @Override public void computeHashArray() { for (int i = 0; i < n; i++) hash[i + 1] = (hash[i] * 53 + ch[i] - 'a') % MH; } public long getHash(int i, int j) { return (hash[j] - hash[i] * mod[j - i] + MH * MH) % MH; } public long getHash(String s) { long h = 0; for (int i = 0; i < s.length(); i++) h = (h * 53 + s.charAt(i) - 'a') % MH; return h; } public long[] getHashArray() { return hash; } public long[] getModArray() { return mod; } } public interface Manacher { public void oddPalindrome(); public void evenPalindrome(); } class Palindrome implements Manacher { private int n; private char[] ch; private int[] oddPal, evenPal; public Palindrome() {} public Palindrome(String s) { this(s.toCharArray()); } public Palindrome(char[] ch) { this.ch = ch; n = ch.length; oddPal = new int[ch.length]; evenPal = new int[ch.length]; oddPalindrome(); evenPalindrome(); } @Override public void oddPalindrome() { for (int i = 0, l = 0, r = -1; i < n; i++) { int k = i > r ? 1 : Math.min(oddPal[r + l - i], r - i); while (0 <= i - k && i + k < n && ch[i - k] == ch[i + k]) k++; oddPal[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } } @Override public void evenPalindrome() { for (int i = 0, l = 0, r = -1; i < n; i++) { int k = i > r ? 0 : Math.min(evenPal[r + l - i + 1], r - i + 1); while (0 <= i - k - 1 && i + k < n && ch[i - k - 1] == ch[i + k]) k++; evenPal[i] = k--; if (i + k > r) { l = i - k - 1; r = i + k; } } } } void printf() { out.print(answer); } void close() { out.close(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][])obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][])obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][])obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T min(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) < 0) m = t[i]; return m; } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T max(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) > 0) m = t[i]; return m; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } // c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c; int[] ext_gcd(int a, int b) { if (b == 0) return new int[] {a, 1, 0 }; int[] vals = ext_gcd(b, a % b); int d = vals[0]; // gcd int p = vals[2]; // int q = vals[1] - (a / b) * vals[2]; return new int[] { d, p, q }; } // find any solution of the equation: ax + by = c using extends gcd boolean find_any_solution(int a, int b, int c, int[] root) { int[] vals = ext_gcd(Math.abs(a), Math.abs(b)); if (c % vals[0] != 0) return false; printf(vals); root[0] = c * vals[1] / vals[0]; root[1] = c * vals[2] / vals[0]; if (a < 0) root[0] *= -1; if (b < 0) root[1] *= -1; return true; } int mod(int x) { return x % MOD; } int mod(int x, int y) { return mod(mod(x) + mod(y)); } long mod(long x) { return x % MOD; } long mod (long x, long y) { return mod(mod(x) + mod(y)); } int lw(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } int lw(int[] f, int l, int r, int k) { // int R = r, m = 0; while (l <= r) { int m = l + r >> 1; // if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } long calc(int base, int exponent) { if (exponent == 0) return 1; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long power(int base, int exponent) { if (exponent == 0) return 1; long m = power(base, exponent >> 1); if (exponent % 2 == 0) return m * m; return base * m * m; } void swap(int[] a, int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparable<Pair<K, V>> { private K k; private V v; Pair() {} Pair(K k, V v) { this.k = k; this.v = v; } K getK() { return k; } V getV() { return v; } void setK(K k) { this.k = k; } void setV(V v) { this.v = v; } void setKV(K k, V v) { this.k = k; this.v = v; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Pair)) return false; Pair<K, V> p = (Pair<K, V>) o; return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0; } @Override public int hashCode() { int hash = 31; hash = hash * 89 + k.hashCode(); hash = hash * 89 + v.hashCode(); return hash; } @Override public int compareTo(Pair<K, V> pair) { return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k); } @Override public Pair<K, V> clone() { return new Pair<K, V>(this.k, this.v); } @Override public String toString() { return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n"); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
07a01d16aa7f9cb16cf9374a89471bf9
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
//-----Nilay Shah----0-// // A new building for SIS// import java.util.*; import java.lang.Math; import java.io.*; public class problemA { public static void main(String args[]) throws java.lang.Exception { Scanner s = new Scanner(System.in); int n = s.nextInt(); if(n<=1) { System.out.println(0); return; } int[] arr = new int[2*n]; for(int i=0;i<2*n;i++) { arr[i]=s.nextInt(); } Arrays.sort(arr); long ans = ((long)(arr[n-1]-arr[0])*(arr[2*n-1]-arr[n])); for(int i=1;i+n<arr.length;i++) { long temp = ((long)(arr[2*n-1]-arr[0])*(arr[i+n-1]-arr[i])); if(temp<ans) ans=temp; } System.out.println(ans); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
71f3fd4d191975389fd16174661efcd9
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
//package contests.CF1012; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = new int[2*n]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } shuffle(arr); Arrays.sort(arr); long ans = 1l*(arr[n-1]-arr[0])*(arr[2*n-1]-arr[n]); for (int i = 1; i+n-1 < 2*n-1; i++) { ans = Math.min(ans, 1l*(arr[i+n-1]-arr[i])*(arr[2*n-1]-arr[0])); } System.out.println(ans); pw.flush(); pw.close(); } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(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();} } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
36e7fd8ffb4ea947e2477a25756ed607
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); n = 2*n; long arr[] = new long[n]; for(int i = 0 ; i < n ; i++) { arr[i] = sc.nextLong(); } Arrays.sort(arr); long min = (arr[n/2 - 1] - arr[0])*(arr[n - 1] - arr[n/2]); for(int i = 1 ; i < n/2 ; i++) { long temp = (arr[i + n/2 - 1] - arr[i])*(arr[n - 1] - arr[0]); if(temp < min) min = temp; } System.out.println(min); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
617c45ebcebc5884f350daf366f1ebea
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.util.*; import java.io.*; public class HelloWorld { public static void main(String []args)throws IOException { int i,j; long z=(long)Math.pow(10,9)+7; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=Integer.parseInt(br.readLine()); long a[]=new long[2*n]; ArrayList<Long> arr=new ArrayList<Long>(); String s[]=br.readLine().split(" "); for(i=0;i<2*n;i++) { long p=Long.parseLong(s[i]); a[i]=p; } Arrays.sort(a); for(i=1;i<=n-1;i++) { long x1=a[0]; long x2=a[i]; long y1=a[i+n-1]; long y2=a[2*n-1]; //out.println(y2+"-"+x1+" "+y1+"-"+x2); long ans=((y2-x1)*(y1-x2)); arr.add(ans); } arr.add(((a[n-1]-a[0])*(a[2*n-1]-a[n]))); Collections.sort(arr); //out.println(arr); out.println(arr.get(0)); out.close(); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output