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
47f48fae90016cb3711820172e1eafa4
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionB { public static void main(String[] args){ new SolutionB().run(); } int next[]; int a[]; int cur[]; int arr[]; int sz = 0; void solve(){ int n = in.nextInt(); a = new int[n]; for(int i = 0; i < n; i++) a[i] = in.nextInt(); next = new int[n]; cur = new int[n]; for(int i = 0; i < n; i++) next[i] = i+1; int m = in.nextInt(); arr = new int[n]; for(int i = 0; i < m; i++){ int k = in.nextInt(); if( k == 1){ int st = in.nextInt()-1; int ad = in.nextInt(); sz = 0; while(st < n && a[st] <= cur[st] + ad){ ad -= (a[st] - cur[st]); arr[sz] = st; cur[st] = a[st]; st = next[st]; sz++; } if(st < n){ cur[st] += ad; } for(int j = 0; j < sz; j++) next[arr[j]] = st; //out.flush(); } else { out.println(cur[in.nextInt()-1]); //out.flush(); } } } PrintWriter out; FastScanner in; public void run(){ in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner{ BufferedReader bf; StringTokenizer st; public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(Exception ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } BigInteger nextBigInteger(){ return new BigInteger(next()); } BigDecimal nextBigDecimal(){ return new BigDecimal(next()); } int[] nextArray(int n){ int x[] = new int[n]; for(int i = 0; i < n; i++){ x[i] = Integer.parseInt(next()); } return x; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
3a2fd675f907c98160876d059f2a06ad
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionB { public static void main(String[] args){ new SolutionB().run(); } int next[]; int a[]; int cur[]; ArrayList<Integer> arr; void solve(){ int n = in.nextInt(); a = new int[n]; for(int i = 0; i < n; i++) a[i] = in.nextInt(); next = new int[n]; cur = new int[n]; for(int i = 0; i < n; i++) next[i] = i+1; int m = in.nextInt(); arr = new ArrayList<Integer>(); for(int i = 0; i < m; i++){ int k = in.nextInt(); if( k == 1){ int st = in.nextInt()-1; int ad = in.nextInt(); arr.clear(); //out.println(st + " " + ad); while(st < n && a[st] <= cur[st] + ad){ arr.add(st); ad -= (a[st] - cur[st]); cur[st] = a[st]; st = next[st]; } if(st < n){ cur[st] += ad; } for(int j:arr){ next[j] = st; } //out.flush(); } else { out.println(cur[in.nextInt()-1]); //out.flush(); } } } PrintWriter out; FastScanner in; public void run(){ in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner{ BufferedReader bf; StringTokenizer st; public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(Exception ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } BigInteger nextBigInteger(){ return new BigInteger(next()); } BigDecimal nextBigDecimal(){ return new BigDecimal(next()); } int[] nextArray(int n){ int x[] = new int[n]; for(int i = 0; i < n; i++){ x[i] = Integer.parseInt(next()); } return x; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
2cc73236b05b8c35b8b37a88187871db
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; public class Vessels { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final int n = Integer.parseInt(br.readLine()); TreeSet<Integer> empty = new TreeSet<Integer>(); long[] filled = new long[n + 2]; long[] capacity = new long[n + 2]; String[] params = br.readLine().split(" "); for (int i = 1; i <= params.length; i++) { capacity[i] = Integer.parseInt(params[i - 1]); empty.add(i); } capacity[capacity.length - 1] = Long.MAX_VALUE; empty.add(capacity.length - 1); final int m = Integer.parseInt(br.readLine()); for (int i = 0; i < m; i++) { params = br.readLine().split(" "); int type = Integer.parseInt(params[0]); if (type == 2) System.out.println(filled[Integer.parseInt(params[1])]); else { long amt = Integer.parseInt(params[2]); int place = empty.higher(-1 + Integer.parseInt(params[1])); while (amt > 0) { // System.out.println("Insert: " + place); long remain = capacity[place] - filled[place]; long insert = Math.min(remain, amt); if (remain <= amt) empty.remove(place); amt -= insert; filled[place] += insert; if(amt > 0) place = empty.higher(place); } // System.out.println(empty); } } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
a1978bbb7a0fd2357cf6ec060e3ca1f8
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Vessels { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int m = sc.nextInt(); int q[] = new int[n]; int nextEmpty[] = new int[n]; for (int i = 0; i < n; i++) { nextEmpty[i] = i + 1; } for (int i = 0; i < m; i++) { int op = sc.nextInt(); if (op == 1) { int p = sc.nextInt(); int x = sc.nextInt(); add(x, p - 1, a, q, nextEmpty); } else { int k = sc.nextInt(); System.out.println(q[k - 1]); } } } /* private static void add(int x, int p, int[] a, int[] q,int[] nextEmpty) { int i = p; while (x>0 && i < a.length) { int qWas = q[i]; q[i] = Math.min(a[i], q[i] + x); x -= q[i] - qWas; i++; } } */ private static void add(int x, int p, int[] a, int[] q, int[] nextEmpty) { int i = p; List<Integer> visited = new ArrayList<Integer>(); int lastNonFull = i + 1; while (x > 0 && i < a.length) { visited.add(i); int qWas = q[i]; q[i] = Math.min(a[i], q[i] + x); x -= q[i] - qWas; i = Math.max(nextEmpty[i], i + 1); if (a[i-1] == q[i-1]) { lastNonFull = i; } } for (int cell : visited) { nextEmpty[cell] = lastNonFull; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
5cd42d4af184acf1783d4167a5a7c68b
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; public class CF { TreeSet<Integer> free = new TreeSet<>(); int[] now; int[] a; int n; void go(int v, int cnt) { Integer x = free.higher(v - 1); if (x == null) { return; } v = x; int can = Math.min(cnt, a[v] - now[v]); cnt -= can; now[v] += can; if (now[v] == a[v]) free.remove(v); if (cnt > 0) go(v + 1, cnt); } void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); for (int i = 0; i < n; i++) free.add(i); int m = in.nextInt(); now = new int[n]; for (int i = 0; i < m; i++) { int type = in.nextInt(); if (type == 1) { go(in.nextInt() - 1, in.nextInt()); } else { out.println(now[in.nextInt() - 1]); } } } FastScaner in; PrintWriter out; void run() { in = new FastScaner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void runWithFiles() { in = new FastScaner(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } public static void main(String[] args) { Locale.setDefault(Locale.US); new CF().run(); } class FastScaner { BufferedReader br; StringTokenizer st; FastScaner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } FastScaner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
6a92893db4b95f2f38ac6370b9fbd27b
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; public class cf371d { static FastIO in = new FastIO(), out = in; public static void main(String[] args) { int n = in.nextInt(); DisjointSet ds = new DisjointSet(n+1); int[] v = new int[n]; int[] cap = new int[n]; for(int i=0; i<n; i++) cap[i] = in.nextInt(); int m = in.nextInt(); for(int i=0; i<m; i++) { int type = in.nextInt(); if(type == 1) { int p = in.nextInt()-1; int x = in.nextInt(); while(x != 0 && p != n) { int toAdd = Math.min(x, cap[p]-v[p]); v[p] += toAdd; x -= toAdd; if(v[p] == cap[p]) ds.union(p, p+1); p = ds.find(p); } } else { int k = in.nextInt()-1; out.println(v[k]); } } out.close(); } static class DisjointSet { int[] p, r; DisjointSet(int s) { p = new int[s]; r = new int[s]; for(int i=0; i<s; i++) p[i] = i; } // make y the parent of x void union(int x, int y) { int a = find(x); int b = find(y); if(a==b) return; p[x] = y; } int find(int x) { int xtmp = x; while(p[xtmp] != xtmp) xtmp = p[xtmp]; while(p[x] != x) { int nx = p[x]; p[x] = xtmp; x = nx; } return x; } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in, System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if (!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if (!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
b021f1631cf77de2f4c2e3b2d9fa1df2
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; public class D_Vessels { private static void addWater(int vessel , int amount) { vessels[vessel] += amount; if (vessels[vessel] > caps[vessel]) { amount = vessels[vessel] - caps[vessel]; vessels[vessel] = caps[vessel]; open.remove(vessel); Integer next = open.higher(vessel); if (next != null) { addWater(next , amount); } } } public static void main(String[] args) throws java.io.IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); final int N = Integer.parseInt(input.readLine()); String[] vals = input.readLine().split(" "); caps = new int[N]; vessels = new int[N]; for (int i = 0 ; i < N ; i++) { caps[i] = Integer.parseInt(vals[i]); open.add(i); } final int M = Integer.parseInt(input.readLine()); for (int i = 0 ; i < M ; i++) { String[] query = input.readLine().split(" "); switch(query[0]) { case "1": addWater(Integer.parseInt(query[1]) - 1 , Integer.parseInt(query[2])); break; case "2": System.out.println(vessels[Integer.parseInt(query[1]) - 1]); break; } } } static int[] caps; static int[] vessels; static TreeSet<Integer> open = new TreeSet<>(); }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
f74b894e560eec276109cdc87650367b
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; public class D371{ 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()); StringTokenizer st = new StringTokenizer(br.readLine(), " "); Node[] nodes = new Node[n]; for(int i = 0; i < n; i++){ nodes[i] = new Node(Integer.parseInt(st.nextToken())); } for(int i = 0; i < n-1; i++){ nodes[i].next = nodes[i+1]; } int m = Integer.parseInt(br.readLine()); for(int i = 0; i < m; i++){ st = new StringTokenizer(br.readLine(), " "); int type = Integer.parseInt(st.nextToken()); if(type == 1){ add(nodes[Integer.parseInt(st.nextToken())-1], Integer.parseInt(st.nextToken())); } else { int x = Integer.parseInt(st.nextToken()); pw.println(nodes[x-1].max - nodes[x-1].cap); } } br.close(); pw.close(); } public static Node add(Node node, int amt){ node.cap -= amt; if(node.cap < 0){ if(node.next != null){ node.next = add(node.next, -node.cap); } node.cap = 0; return node.next; } return node; } static class Node{ public int cap; public int max; public Node next; public Node(int c){ cap = c; max = c; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
c8873692cd6293140379ccf8a49665ac
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Aleksandr */ public class Main { static int[] currentWater; // static ArrayList<Integer> notFull = new ArrayList<>(); static TreeSet<Integer> notFull = new TreeSet<>(); public static void main(String[] args) { //ArrayList<Integer> original = new ArrayList<>(); Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] v = new int[n]; for (int i = 0; i < n; i++) { v[i] = s.nextInt(); if (v[i] != 0) { notFull.add(i); } } currentWater = new int[n]; int m = s.nextInt(); for (int i = 0; i < m; i++) { int query = s.nextInt(); if (query == 1) { int pi = s.nextInt() - 1; int xi = s.nextInt(); zalit(xi, pi, v); } if (query == 2) { int ki = s.nextInt() - 1; System.out.println(currentWater[ki]); } } } private static void zalit(int pi, int xi, int[] v) { if (xi == 3) { xi = 3; } int n = currentWater.length; while (pi > 0) { if (xi >= n) { return; } if (xi == n - 1 && currentWater[n - 1] == v[n - 1]) { return; } if (currentWater[xi] == v[xi]) { //xi = binarSearchNearestNotFull(xi); if (notFull.isEmpty() || notFull.last() <= xi) { return; } xi = notFull.higher(Integer.valueOf(xi)); // if (xi == -1) { // return; // } } else { if (currentWater[xi] + pi > v[xi]) { pi -= v[xi] - currentWater[xi]; currentWater[xi] = v[xi]; notFull.remove(Integer.valueOf(xi)); } else { currentWater[xi] += pi; if (currentWater[xi] == v[xi]) { notFull.remove(Integer.valueOf(xi)); } pi = 0; } } } } // private static int binarSearchNearestNotFull(int x) { // int first = 0; // int last = notFull.size(); // int mid = first + (last - first) / 2; // if (notFull.size() == 0) { // return -1; // } // if (notFull.get(0) > x) { // return notFull.get(0); // } // if (notFull.get(last - 1) < x) { // return -1; // } // while (first < last) { // if (x <= notFull.get(mid)) { // last = mid; // } else { // first = mid + 1; // } // mid = first + (last - first) / 2; // } // return notFull.get(last); // } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
970ca32150fc1828408cdbd5fe7c28bb
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Codeforces { public static void main(String[] args) { CustomInputReader in = new CustomInputReader(System.in); Task solver = new Task(); solver.solve(in); } } class Task { long[] capacity, filled; int[] f; public void solve(CustomInputReader in) { int n = in.nextInt(); capacity = new long[n + 1]; filled = new long[n + 1]; f = new int[n + 1]; for (int i = 1; i <= n; i++) { capacity[i] = in.nextLong(); f[i] = i; } int m = in.nextInt(); for (int i = 0; i < m; i++) { int operation = in.nextInt(); if (operation == 1) { int addTo = in.nextInt(); long add = in.nextLong(); fill(addTo, add); } else if (operation == 2) { int node = in.nextInt(); System.out.println(filled[node]); } } } private void fill(int addTo, long add) { for (int j = get(addTo); j < filled.length; j = get(j)) { if (filled[j] + add <= capacity[j]) { filled[j] += add; return; } add -= capacity[j] - filled[j]; filled[j] = capacity[j]; if (j == filled.length - 1) return; f[j] = get(j + 1); } } int get(int x) { if (f[x] == x) { return x; } f[x] = get(f[x]); return f[x]; } } class CustomInputReader { public BufferedReader reader; public StringTokenizer tokenizer; public CustomInputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
98b7459ed1c5d0462a715b652f3808ff
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main implements Runnable { // leave empty to read from stdin/stdout private static final String TASK_NAME_FOR_IO = ""; // file names private static final String FILE_IN = TASK_NAME_FOR_IO + ".in"; private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out"; BufferedReader in; PrintWriter out; StringTokenizer tokenizer = new StringTokenizer(""); public static void main(String[] args) { new Thread(new Main()).start(); } int n; int []a, v; int []p, rank; private void solve() throws IOException { n = nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) a[i] = nextInt(); v = new int[n]; p = new int[n + 1]; for(int i = 1; i <= n; ++i) p[i] = i; rank = new int[n + 1]; int q = nextInt(); while(q-- > 0) { int type = nextInt(); if (type == 1) { int c = nextInt() - 1, V = nextInt(); while(V > 0) { c = find(c); if (c == n) break; if (a[c] - v[c] > 0) { int min = Math.min(V, a[c] - v[c]); v[c] += min; V -= min; if (a[c] == v[c]) { union(c, c + 1); } } } }else { int c = nextInt() - 1; out.println(v[c]); } } } private int find(int x) { if (p[x] != x) return p[x] = find(p[x]); return x; } private void union(int a, int b) { a = find(a); b = find(b); if (a == b) return; // if (rank[a] < rank[b]) { // int tmp = a; // a = b; // b = tmp; // } // p[b] = a; // if (rank[a] == rank[b]) ++rank[a]; p[a] = b; } public void run() { long timeStart = System.currentTimeMillis(); boolean fileIO = TASK_NAME_FOR_IO.length() > 0; try { if (fileIO) { in = new BufferedReader(new FileReader(FILE_IN)); out = new PrintWriter(new FileWriter(FILE_OUT)); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } solve(); in.close(); out.close(); } catch (IOException e) { throw new IllegalStateException(e); } long timeEnd = System.currentTimeMillis(); if (fileIO) { System.out.println("Time spent: " + (timeEnd - timeStart) + " ms"); } } private String nextToken() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private BigInteger nextBigInt() throws IOException { return new BigInteger(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
2c8ee2ea57e07ae0594c46c17b99d2c5
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class D { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); long[]a = new long[n+2], b = new long[n+2]; int[]next = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextLong(); next[i] = i+1; } a[n+1] = (long) 1e18; int m = nextInt(); ArrayList<Integer> order = new ArrayList<>(); for (int i = 1; i <= m; i++) { int t = nextInt(); if (t==1) { int p = nextInt(); int x = nextInt(); order.clear(); while (x > 0) { long c = Math.min(a[p]-b[p], x); x -= c; b[p] += c; order.add(p); if (x != 0) p = next[p]; else { for (int j : order) { if (j != p) next[j] = p; } } } } else { int k = nextInt(); pw.println(b[k]); } } pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
d9b4b2b222cb59c789f22cbe940be918
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; 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 */ 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 { long[] a; long[] b; int[] rightMost; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); } int q = in.nextInt(); StringBuilder res = new StringBuilder(); b = new long[n]; rightMost = new int[n]; for (int i = 0; i < n; i++) { rightMost[i] = i + 1; } for (int i = 0; i < q; i++) { int type = in.nextInt(); int p = in.nextInt() - 1; if (type == 2) { res.append(b[p]); res.append("\n"); } else { long x = in.nextLong(); go(p, x); } } out.println(res); } int go(int u, long x) { if (u >= rightMost.length) return u; b[u] += x; long remain = Math.max(0, b[u] - a[u]); b[u] -= remain; if (remain == 0) return u; return rightMost[u] = go(rightMost[u], remain); } } 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
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
67c7d5a5ae797200919d96c9cbbf737d
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class D { public static void main(String args[]) throws Exception{ int n = readInt(); int[] pointTo = new int[n+1]; int[] capacity = new int[n+1]; int[] startCap = new int[n+1]; for(int i = 1; i <= n; i++){ pointTo[i] = i+1; capacity[i] = readInt(); startCap[i] = capacity[i]; } int m = readInt();; for(int i = 0; i < m; i++){ int a = readInt(); if(a == 1){ int p = readInt(); int x = readInt(); fill(p, pointTo, capacity, x); } else if(a == 2){ int k = readInt(); System.out.println(startCap[k] - capacity[k]); } } } public static int fill(int index, int[] pointTo, int[] capacity, int x){ if(x > capacity[index]){ x -= capacity[index]; capacity[index] = 0; if(index == pointTo.length-1){ return index; } return (pointTo[index] = fill(pointTo[index], pointTo, capacity, x)); } else{ capacity[index] -= x; return index; } } static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(" "); static String readString() throws Exception{ while(!st.hasMoreTokens()){ st = new StringTokenizer(stdin.readLine()); } return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
7a9b45a883468f8b22f9d3d6b78190b3
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.*; import java.io.*; public class D { public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st= null; static String nx() throws Exception { for (;st == null || ! st.hasMoreTokens();){ String k1 = in.readLine(); if (k1 == null) return null; st = new StringTokenizer(k1); } return st.nextToken(); } static int ni() throws Exception { return Integer.parseInt(nx()); } static long nl() throws Exception { return Long.parseLong(nx()); } public static void main(String[] args)throws Exception { new D(); } int nnn1 = 0; int[] cap = null; int[] have = null; int q1 = 0; TreeMap<Integer,Integer> tail = new TreeMap(); D() throws Exception { nnn1 = ni(); cap = new int[nnn1]; have = new int[nnn1]; for (int i =0; i < nnn1; tail.put(i, i), i++); for (int i =0; i < nnn1;i++){ cap[i] = ni(); } q1 = ni(); for (int i =0; i < q1; i++){ int type = ni(); if (type == 1){ int id1 = ni() -1; int am = ni(); // px("type",i,type,id1,am); pour(id1,am); } else { int query = ni() - 1; // px("type",i,type,query); out.println(have[query]); } // px(cap); // px(have); // px(tail); // px("-------"); } out.flush(); } PrintWriter out = new PrintWriter(System.out); void pour(int idx, int n1){ // px(idx,n1); if (idx >= nnn1) return; int head = tail.floorKey(idx); int left = n1; for (;;){ if (left <= 0) break; int t1 = tail.get(head); int next = have[t1] + left; if (next < cap[t1]){ have[t1] = next; break; } else { int used = cap[t1] - have[t1]; left -= used; have[t1] = cap[t1]; Integer after = tail.higherKey(head); if (after == null) return; int newtail = tail.get(after); tail.put(head, newtail); tail.remove(after); } } } static void add(Map<Integer,Integer> m1, int n1){ if (m1.containsKey(n1)){ m1.put(n1, m1.get(n1)+1); } else m1.put(n1, 1); } static void px(Object ...objects){ System.out.println(Arrays.deepToString(objects)); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
9faa2b33176560af356be17f3a11452b
train_002.jsonl
1406907000
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4n places.
256 megabytes
import java.io.*; import java.util.*; public class Main { static ArrayList<Integer>[] adj; static int[] degree; static boolean[] marked; static ArrayList<Integer> path; public static void main(String[] args) { BufferedReader br = new BufferedReader( new InputStreamReader( System.in) , 8* 1024); Scanner sc = new Scanner( br); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( System.out) , 8*1024); PrintWriter pw = new PrintWriter( bw ); int n , m , u , v ; n = sc.nextInt(); m = sc.nextInt(); adj = ( ArrayList<Integer>[]) new ArrayList[n]; path = new ArrayList<Integer>(1000000); for( int i = 0 ; i < n ; ++i ) adj[i] = new ArrayList<Integer>(); degree = new int[n]; marked = new boolean[n]; for( int i = 0 ; i < m ; ++i ) { u = sc.nextInt(); v = sc.nextInt(); u--; v--; adj[u].add(v); adj[v].add(u); } for( int i = 0 ; i < n ; ++i ) degree[i] = sc.nextInt(); // for(int i = 0 ; i < n ; ++i ) // { // System.out.println( i + " : " + adj[i]); // } int i = 0 ; for(i = 0 ; i < n ; ++i ) if( degree[i ] == 1 ) { startAt(i); break; } if( i == n ) pw.println("0"); else { boolean flag = false; for( int j = 0 ; j < n ; ++j ) { if( !marked[j] && degree[j]==1 ) flag = true; } if( flag ) pw.println("-1"); else { pw.println(path.size()); for( int x : path) pw.print( (x+1) + " " ); } } pw.close(); } static void startAt(int root) { dfs( root , -1 ); if( degree[root] == 1 ) { path.remove( path.size() - 1 ); } } static void dfs( int node , int parent ) { marked[node] = true; path.add( node ); changeDegree( node) ; int count = 0 ; for(int i : adj[node] ) { if( !marked[i] ) { count ++; dfs( i , node ); path.add(node); changeDegree(node); } } if( degree[node] == 1 && parent != -1 ) { path.add(parent); changeDegree(parent); path.add(node); changeDegree( node ) ; } } static void changeDegree(int i ) { degree[i] = (degree[i] + 1 )%2; } }
Java
["3 2\n1 2\n2 3\n1 1 1", "5 7\n1 2\n1 3\n1 4\n1 5\n3 4\n3 5\n4 5\n0 1 0 1 0", "2 0\n0 0"]
1 second
["3\n1 2 3", "10\n2 1 3 4 5 4 5 4 3 1", "0"]
null
Java 7
standard input
[ "dfs and similar" ]
203be1bbb9bb3648aaa63e81ec2a9db5
The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105) — the number of places and the number of roads in Ponyville. Each of the following m lines contains two integers ui, vi (1 ≤ ui, vi ≤ n; ui ≠ vi), these integers describe a road between places ui and vi. The next line contains n integers: x1, x2, ..., xn (0 ≤ xi ≤ 1) — the parity of the number of times that each place must be visited. If xi = 0, then the i-th place must be visited even number of times, else it must be visited odd number of times.
2,200
Output the number of visited places k in the first line (0 ≤ k ≤ 4n). Then output k integers — the numbers of places in the order of path. If xi = 0, then the i-th place must appear in the path even number of times, else i-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct. If there is no required path, output -1. If there multiple possible paths, you can output any of them.
standard output
PASSED
d4e33ff7257174ae1dd4c347385a46b3
train_002.jsonl
1406907000
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4n places.
256 megabytes
import java.io.*; import java.util.*; public class Main { static ArrayList<Integer>[] adj; static int[] degree; static boolean[] marked; static ArrayList<Integer> path; public static void main(String[] args) { BufferedReader br = new BufferedReader( new InputStreamReader( System.in) , 8* 1024); Scanner sc = new Scanner( br); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( System.out) , 8*1024); PrintWriter pw = new PrintWriter( bw ); int n , m , u , v ; n = sc.nextInt(); m = sc.nextInt(); adj = ( ArrayList<Integer>[]) new ArrayList[n]; path = new ArrayList<Integer>(1000000); for( int i = 0 ; i < n ; ++i ) adj[i] = new ArrayList<Integer>(100); degree = new int[n]; marked = new boolean[n]; for( int i = 0 ; i < m ; ++i ) { u = sc.nextInt(); v = sc.nextInt(); u--; v--; adj[u].add(v); adj[v].add(u); } for( int i = 0 ; i < n ; ++i ) degree[i] = sc.nextInt(); // for(int i = 0 ; i < n ; ++i ) // { // System.out.println( i + " : " + adj[i]); // } int i = 0 ; for(i = 0 ; i < n ; ++i ) if( degree[i ] == 1 ) { startAt(i); break; } if( i == n ) pw.println("0"); else { boolean flag = false; for( int j = 0 ; j < n ; ++j ) { if( !marked[j] && degree[j]==1 ) flag = true; } if( flag ) pw.println("-1"); else { pw.println(path.size()); for( int x : path) pw.print( (x+1) + " " ); } } pw.close(); } static void startAt(int root) { dfs( root , -1 ); if( degree[root] == 1 ) { path.remove( path.size() - 1 ); } } static void dfs( int node , int parent ) { marked[node] = true; path.add( node ); changeDegree( node) ; int count = 0 ; for(int i : adj[node] ) { if( !marked[i] ) { count ++; dfs( i , node ); path.add(node); changeDegree(node); } } if( degree[node] == 1 && parent != -1 ) { path.add(parent); changeDegree(parent); path.add(node); changeDegree( node ) ; } } static void changeDegree(int i ) { degree[i] = (degree[i] + 1 )%2; } }
Java
["3 2\n1 2\n2 3\n1 1 1", "5 7\n1 2\n1 3\n1 4\n1 5\n3 4\n3 5\n4 5\n0 1 0 1 0", "2 0\n0 0"]
1 second
["3\n1 2 3", "10\n2 1 3 4 5 4 5 4 3 1", "0"]
null
Java 7
standard input
[ "dfs and similar" ]
203be1bbb9bb3648aaa63e81ec2a9db5
The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105) — the number of places and the number of roads in Ponyville. Each of the following m lines contains two integers ui, vi (1 ≤ ui, vi ≤ n; ui ≠ vi), these integers describe a road between places ui and vi. The next line contains n integers: x1, x2, ..., xn (0 ≤ xi ≤ 1) — the parity of the number of times that each place must be visited. If xi = 0, then the i-th place must be visited even number of times, else it must be visited odd number of times.
2,200
Output the number of visited places k in the first line (0 ≤ k ≤ 4n). Then output k integers — the numbers of places in the order of path. If xi = 0, then the i-th place must appear in the path even number of times, else i-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct. If there is no required path, output -1. If there multiple possible paths, you can output any of them.
standard output
PASSED
267b1264315e99ac26aba3fb55a25aac
train_002.jsonl
1406907000
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4n places.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main{ FastScanner in; PrintWriter out; ArrayList<Integer>[] list; int[] odd; boolean[] used; ArrayList<Integer> ans; public int dfs(int v) { int c = odd[v]; used[v] = true; for (int to : list[v]) if (!used[to]) c = Math.max(c, dfs(to)); return c; } public void dfs1(int v, int p) { used[v] = true; odd[v] = 1-odd[v]; ans.add(v); for (int to : list[v]) if (!used[to]) { dfs1(to, v); ans.add(v); odd[v] = 1-odd[v]; } if (odd[v] == 1 && p != -1) { odd[v] = 0; odd[p] = 1-odd[p]; ans.add(p); ans.add(v); } } public void solve() { int n = in.nextInt(); int m = in.nextInt(); list = new ArrayList[n]; for (int i = 0; i < n; i++) list[i] = new ArrayList<>(); int a, b; for (int i = 0; i < m; i++) { a = in.nextInt(); --a; b = in.nextInt(); --b; list[a].add(b); list[b].add(a); } odd = new int[n]; for (int i = 0; i < n; i++) odd[i] = in.nextInt(); used = new boolean[n]; for (int i = 0; i < n; i++) used[i] = false; int cnt = 0; for (int i = 0; i < n; i++) if (!used[i]) { cnt += dfs(i); } if (cnt == 0) { out.println(0); } else if (cnt > 1) { out.println(-1); } else { for (int i = 0; i < n; i++) used[i] = false; ans = new ArrayList<>(); for (int i = 0; i < n; i++) if (odd[i] == 1) { dfs1(i, -1); if (odd[i] == 1) ans.remove(0); } out.println(ans.size()); for (int x : ans) out.print((x+1) + " "); out.println(); } } public void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) { new Main().run(); } 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()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2\n1 2\n2 3\n1 1 1", "5 7\n1 2\n1 3\n1 4\n1 5\n3 4\n3 5\n4 5\n0 1 0 1 0", "2 0\n0 0"]
1 second
["3\n1 2 3", "10\n2 1 3 4 5 4 5 4 3 1", "0"]
null
Java 7
standard input
[ "dfs and similar" ]
203be1bbb9bb3648aaa63e81ec2a9db5
The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105) — the number of places and the number of roads in Ponyville. Each of the following m lines contains two integers ui, vi (1 ≤ ui, vi ≤ n; ui ≠ vi), these integers describe a road between places ui and vi. The next line contains n integers: x1, x2, ..., xn (0 ≤ xi ≤ 1) — the parity of the number of times that each place must be visited. If xi = 0, then the i-th place must be visited even number of times, else it must be visited odd number of times.
2,200
Output the number of visited places k in the first line (0 ≤ k ≤ 4n). Then output k integers — the numbers of places in the order of path. If xi = 0, then the i-th place must appear in the path even number of times, else i-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct. If there is no required path, output -1. If there multiple possible paths, you can output any of them.
standard output
PASSED
35946bbbeb0bc45252b1b0c59962dc0d
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class frtrt { public static void main(String[] args) { Scanner sc=new Scanner (System.in); int n=sc.nextInt(); int ar[]=new int[n]; for(int i=0;i<n;i++) { ar[i]=sc.nextInt(); } for(int i=1;i<n;i++) { ar[i]=ar[i]+ar[i-1]; } int k=sc.nextInt(); Arrays.sort(ar); for(int i=0;i<k;i++) { int x=sc.nextInt(); int u=Arrays.binarySearch(ar, x); if(u>=0) { System.out.println(u+1); } else{ System.out.println(-u); } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
d6654e570df098b79bde6a66a30c6dcb
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class worm { public static void main(String[] args) { // TODO Auto-generated method stub int test, n, m, i, low,high, mid; Scanner scan =new Scanner(System.in); n=scan.nextInt(); int[] arr=new int[n+1]; arr[0]=0; for(i=1; i<n+1; i++){ m=scan.nextInt(); arr[i]=m+arr[i-1]; } m=scan.nextInt(); for(i=0; i<m; i++){ test=scan.nextInt(); low=1; high=n; while(low<=high){ mid=(low+high)/2; if(test<=arr[mid] && test>arr[mid-1]){ System.out.println(mid); break; } else if(test>arr[mid]){ low=mid+1; } else high=mid-1; } } scan.close(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
2838a641fa210b881bb6b75fc4c378e6
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class worm { public static void main(String[] args) { // TODO Auto-generated method stub int test, n, m, i, low,high, mid; Scanner scan =new Scanner(System.in); n=scan.nextInt(); int[] arr=new int[n+1]; arr[0]=0; for(i=1; i<n+1; i++){ m=scan.nextInt(); arr[i]=m+arr[i-1]; } m=scan.nextInt(); for(i=0; i<m; i++){ test=scan.nextInt(); low=1; high=n; while(low<high){ mid=(low+high)/2; if(test>arr[mid]){ low=mid+1; } else if(test<=arr[mid]) high=mid; } System.out.println(high); } scan.close(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
e016cbd64fca70067123a3d885ee15af
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; public class NewClass { // static int answer = -1; //static LinkedHashMap<Integer,Integer> hm=new LinkedHashMap<Integer,Integer>(); //static int[] arr; public static void main (String[]args){ Scanner in = new Scanner(System.in); int size=in.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); int sum=0; int[] arr = new int[size]; for (int i = 1 ;i<=size; i++){ int b = in.nextInt(); for (int j = 0 ;j<b;j++){ a.add(i); } } int size1 = in.nextInt(); int answers[] = new int[size1]; for(int i = 0 ;i<size1;i++){ int v = in.nextInt(); answers[i] = v; } for (int i = 0;i<answers.length; i++) { System.out.println(a.get(answers[i]-1)); } } /* arr = new int[per+1]; System.out.println("Size: "+per); int size=in.nextInt(); arr[i]=size; sum+=size; } /*Print------------------------------- for(int i=0;i<arr.length-1;i++){ System.out.print(arr[i]+" "); } /*Print out------------------------- System.out.println("Sum "+sum); int b=0,d=0; int []ansArr= new int[sum]; int c=1; for(int j=0;j<arr.length;j++){ for(int i=b;i<arr[j];i++){ ansArr[i]=c; d++; } c++; System.out.println(j+" "+d); b=d; } for(int i=0;i<ansArr.length-1;i++){ System.out.print(ansArr[i]+" "); } //hm.put(count, b); //count++; }/* int c=in.nextInt(); /*int forAns=in.nextInt(); for(int i=0;i<forAns;i++){ System.out.println(a[in.nextInt()]); } //System.out.println(hm); */}
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
bd1760d7eba320054bbe5c203ade77a3
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class Worms { public static void main(String[] args) { Scanner sca = new Scanner(System.in); int numero_frascos = sca.nextInt(); int Ngusanos = 0; int[] cantidad_frasco = new int[numero_frascos]; int i, j, temp; for (i = 0; i < numero_frascos; i++) { cantidad_frasco[i] = sca.nextInt(); Ngusanos += cantidad_frasco[i]; } int[] vec_gusanos = new int[Ngusanos]; int contador = 1; for (i = 1; i <= cantidad_frasco.length; i++) { temp = cantidad_frasco[i - 1]; for (j = 0; j < temp; j++) { vec_gusanos[contador - 1] = i; contador++; } } int jugosos = sca.nextInt(); int[] vec_jugosos = new int[jugosos]; for (i = 0; i < jugosos; i++) { vec_jugosos[i] = sca.nextInt(); } for (i = 0; i < vec_jugosos.length; i++) { if (vec_jugosos[i] <= vec_gusanos.length) { System.out.println(vec_gusanos[vec_jugosos[i] - 1]); } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
43f6d10c2420a42692f9890ce254240c
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class Worms { public static void main(String[] args) { Scanner sca = new Scanner(System.in); int numero_frascos = sca.nextInt(); int Ngusanos = 0; int[] cantidad_frasco = new int[numero_frascos]; int i, j, temp; for (i = 0; i < numero_frascos; i++) { cantidad_frasco[i] = sca.nextInt(); Ngusanos += cantidad_frasco[i]; } int[] vec_gusanos = new int[Ngusanos]; int contador = 1; for (i = 1; i <= cantidad_frasco.length; i++) { temp = cantidad_frasco[i - 1]; for (j = 0; j < temp; j++) { vec_gusanos[contador - 1] = i; contador++; } } int jugosos = sca.nextInt(); int[] vec_jugosos = new int[jugosos]; for (i = 0; i < jugosos; i++) { vec_jugosos[i] = sca.nextInt(); } for (i = 0; i < vec_jugosos.length; i++) { if (vec_jugosos[i] <= vec_gusanos.length) { System.out.println(vec_gusanos[vec_jugosos[i] - 1]); } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
ae694d511fb5c5fc0d051de03bc51cd9
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { Solution2.main(); } // TreeSet solution; BufferedReader necessary to meet time limits. private static class Solution1 { public static void main() throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); TreeSet<PileWithIndex> allOfOurPiles = new TreeSet<>(); int numWormPiles = Integer.parseInt(bufferedReader.readLine()); String[] inputs = bufferedReader.readLine().split(" "); int lastLast = 0; for (int p = 0; p < numWormPiles; p++) { int pileSize = Integer.parseInt(inputs[p]); int lastWormInThePile = lastLast+pileSize; allOfOurPiles.add(new PileWithIndex(p+1, lastWormInThePile)); lastLast = lastWormInThePile; } // Answer our queries! PileWithIndex pileForQueries = new PileWithIndex(-1, -1); int numQueries = Integer.parseInt(bufferedReader.readLine()); inputs = bufferedReader.readLine().split(" "); for (int q = 0; q < numQueries; q++) { int desiredWorm = Integer.parseInt(inputs[q]); // Find me the pileNumber of the lowest pile whose lastWormInThePile is >= desiredWorm. pileForQueries.lastWormInThePile = desiredWorm; System.out.println(allOfOurPiles.ceiling(pileForQueries).pileNumber); } } private static class PileWithIndex implements Comparable<PileWithIndex> { public int pileNumber; public int lastWormInThePile; public PileWithIndex(int pileNumber, int lastWormInThePile) { this.pileNumber = pileNumber; this.lastWormInThePile = lastWormInThePile; } @Override public int compareTo(PileWithIndex other) { // We want to order according to lastWormInPile return lastWormInThePile - other.lastWormInThePile; } } } // Better, binary search solution private static class Solution2 { public static void main() throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int numPiles = Integer.parseInt(bufferedReader.readLine()); String[] inputs = bufferedReader.readLine().split(" "); int[] cumSum = new int[numPiles]; cumSum[0] = Integer.parseInt(inputs[0]); for (int p = 1; p < numPiles; p++) { cumSum[p] = cumSum[p-1]+Integer.parseInt(inputs[p]); } int numQueries = Integer.parseInt(bufferedReader.readLine()); inputs = bufferedReader.readLine().split(" "); for (int q = 0; q < numQueries; q++) { int desiredWorm = Integer.parseInt(inputs[q]); // Find that correct pile with binary search! System.out.println(findLowestGTE(cumSum, desiredWorm)+1); } } public static int findLowestGTE(int[] cumSum, int target) { int lo = 0, hi = cumSum.length-1, mid = 0; while (lo < hi) { mid = lo+((hi-lo) / 2); if (target > cumSum[mid]) { lo = mid+1; } else if (target < cumSum[mid]) { // Could be it, but only if thing left of mid is strictly less than target. hi = mid; } else { // They're equal, so it must be the one! return mid; } } return lo; } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
e1db298c31c312f80231d3a488170f27
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { Solution1.main(); } // TreeSet solution private static class Solution1 { public static void main() throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); TreeSet<PileWithIndex> allOfOurPiles = new TreeSet<>(); int numWormPiles = Integer.parseInt(bufferedReader.readLine()); String[] inputs = bufferedReader.readLine().split(" "); int lastLast = 0; for (int p = 0; p < numWormPiles; p++) { int pileSize = Integer.parseInt(inputs[p]); int lastWormInThePile = lastLast+pileSize; allOfOurPiles.add(new PileWithIndex(p+1, lastWormInThePile)); lastLast = lastWormInThePile; } // Answer our queries! PileWithIndex pileForQueries = new PileWithIndex(-1, -1); int numQueries = Integer.parseInt(bufferedReader.readLine()); inputs = bufferedReader.readLine().split(" "); for (int q = 0; q < numQueries; q++) { int desiredWorm = Integer.parseInt(inputs[q]); // Find me the pileNumber of the lowest pile whose lastWormInThePile is >= desiredWorm. pileForQueries.lastWormInThePile = desiredWorm; System.out.println(allOfOurPiles.ceiling(pileForQueries).pileNumber); } } private static class PileWithIndex implements Comparable<PileWithIndex> { public int pileNumber; public int lastWormInThePile; public PileWithIndex(int pileNumber, int lastWormInThePile) { this.pileNumber = pileNumber; this.lastWormInThePile = lastWormInThePile; } @Override public int compareTo(PileWithIndex other) { // We want to order according to lastWormInPile return lastWormInThePile - other.lastWormInThePile; } } } // Better, binary search solution private static class Solution2 { public static void main() { } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
d5d4ef02a803a19be7846632bfc910c8
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class problemA{ public static void main (String []args ) { Scanner s= new Scanner(System.in); int n=s.nextInt(); int m=0; int []arr=new int[20000100]; for(int i=0;i<n;i++) { int x =s.nextInt(); for(int j=0;j<x;j++) { arr[++m]=i+1; } } int t; t=s.nextInt(); while(t!=0) { int x2; x2=s.nextInt(); System.out.println(arr[x2]); t--; } }}
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 8
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
324b94e9e6134edab5eef571910edd07
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; public class prac2 { public static void main(String[] ar) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(br.readLine()); String[] s = br.readLine().split(" "); int[] a = new int[n]; int[] b = new int[n]; a[0] = Integer.parseInt(s[0]); b[0] = a[0]; for(int i = 1 ;i < n; ++i) { a[i] = Integer.parseInt(s[i]); b[i] = a[i] + b[i - 1]; } int k = Integer.parseInt(br.readLine()); String[] kval = br.readLine().split(" "); for(int i = 0; i < k ; ++i){ int val = Integer.parseInt(kval[i]); System.out.println(binarySearch(val, b, a, 0, n - 1)); } } private static int binarySearch(int val, int[] b, int[] a,int low, int high) { int mid = (low + high) / 2; while(true){ mid = (low + high) / 2; if(val <= b[mid] && val > (b[mid] - a[mid])) { return mid+1; }else if(b[mid] > val) high = mid - 1; else low = mid + 1; } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
43634e949fe7966414e26b2cb7e26d79
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; /* * 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 sataev_mb */ public class B271 { /** * @param args the command line arguments */ static int a[]; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(in.readLine()); args = in.readLine().split(" "); a = new int[args.length]; a[0] = Integer.parseInt(args[0]); for (int i = 1; i < args.length; i++) { a[i] = Integer.parseInt(args[i]) + a[i - 1]; } int m = Integer.parseInt(in.readLine()); args = in.readLine().split(" "); for (int i = 0; i < m; i++) { out.write((1 + search(0, n - 1, Integer.parseInt(args[i]))) + "\n"); } out.flush(); out.close(); } static int search(int s, int e, int val) { if (s == e) { return s; } else if (s == 0 && val < a[s]) { return 0; } else if (e == a.length - 1 && val >= a[e]) { return e; } else { if (val <= a[e] && val > a[e - 1]) { return e; } else { if (val > a[(e + s) / 2]) { return search((e + s) / 2, e, val); } else { return search(s, (e + s) / 2, val); } } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
b2c2fb2c4606dfb23e70bc7abb12abc5
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { //Locale.setDefault (Locale.US); Reader in = new Reader(); StringBuilder out = new StringBuilder(); int n, m, t, c; ArrayList<Integer> pile = new ArrayList<Integer>(); //for (int i = 0; i < 3; i++) { n = in.nextInt(); pile.clear(); pile.add(0); c = 1; for (int j = 0; j < n; j++, c++) { t = in.nextInt(); for (int k = 0; k < t; k++) pile.add(c); } m = in.nextInt(); for (int j = 0; j < m; j++) out.append(pile.get(in.nextInt())+"\n"); } System.out.print(out); out = new StringBuilder(); } static class Reader { BufferedReader br; StringTokenizer st; Reader() { // To read from the standard input br = new BufferedReader(new InputStreamReader(System.in)); } Reader(int i) throws IOException { // To read from a file br = new BufferedReader(new FileReader("Sample Input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
36f2f1365f29d68140d8d23ad28f55c4
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
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 br= new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int arr[]=new int[n]; String s[]=(br.readLine()).split(" "); for(int i=0; i<n; i++) { int t= Integer.parseInt(s[i]); if(i==0) { arr[i]=t; continue; } arr[i]=t+arr[i-1]; } int m = Integer.parseInt(br.readLine()); String l[]=(br.readLine()).split(" "); for(int i=0; i<m; i++) { int check = Integer.parseInt(l[i]); int retVal = Arrays.binarySearch(arr,check); if(retVal<0) { retVal=(retVal+1)*-1; } System.out.println(retVal+1); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
c8b60ba8a6161a68c5248cfd88afa5f3
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class exe { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long a[] = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextLong() + a[i - 1]; } int m = in.nextInt(); for (int i = 1; i <= m; i++) { int x = in.nextInt(); System.out.println(bs(x, a)); } } private static int bs(int x, long[] a) { int l = 0, r = a.length - 1; while (l <= r) { int mid = (l + r) / 2; if (x == a[mid]) { return mid; } if (x > a[mid]) l = mid + 1; else r = mid - 1; } return l; } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
c7ad1ddca2cd94c7b8aab018a4a27cbf
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int MAX = (int)1e6 + 1; int[] worm = new int[MAX]; int[] a = new int[n+1]; for(int i = 1; i <= n; ++i){ a[i] = a[i-1] + in.nextInt(); } for(int i = 1; i <= n; ++i){ for(int j = a[i-1]+1; j <= a[i]; ++j){ worm[j] = i; } } int q = in.nextInt(); int query; for(int i = 0; i < q; ++i){ query = in.nextInt(); out.println(worm[query]); } } } 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
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
dfb3b87800018505578e6b839be70cae
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TB { public void solve(int n, int[] a, int m, int[] q) { int[][] sum = new int[n][2]; sum[0][0] = 1; sum[0][1] = a[0]; for (int i = 1; i < n; i ++) { sum[i][0] = sum[i - 1][1] + 1; sum[i][1] = sum[i - 1][1] + a[i]; } int[] ans = new int[m]; for (int i = 0; i < m; i ++) { int left = 1; int right = n; while (left <= right) { int mid = left + (right - left) / 2; if (q[i] <= sum[mid - 1][1] && q[i] >= sum[mid - 1][0]) { ans[i] = mid; break; } else if (q[i] < sum[mid - 1][0]) { right = mid - 1; } else if (q[i] > sum[mid - 1][1]) { left = mid + 1; } } } for (int i : ans) System.out.println(i); } public static void main(String[] args) { FastScanner in = new FastScanner(); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i ++) a[i] = in.nextInt(); int m = in.nextInt(); int[] q = new int[m]; for (int i = 0; i < m; i ++) q[i] = in.nextInt(); new TB().solve(n, a, m, q); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
e18acadc7b1882f4b3690f9030daac6a
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; import java.util.*; public class Worms { public static void main(String[] args) throws IOException { int n,m,worm; int[] piles; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; n = Integer.parseInt(br.readLine()); piles = new int[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;++i) { piles[i] = Integer.parseInt(st.nextToken()); if(i>0) piles[i]+=piles[i-1]; } m = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); for(int i=0;i<m;++i) { worm = Integer.parseInt(st.nextToken()); /* binary search */ int low=0,high=n-1,mid=0; while(low<=high) { mid = (low+high)/2; if( piles[mid] < worm ) low = mid+1; else if( piles[mid] == worm) break; else high = mid-1; } if(piles[mid]>=worm) System.out.println(mid+1); else System.out.println(mid+2); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
1d056f976c065ff797e07f72a24a9abd
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String argv []) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int a[] = new int[1000000]; int previous = 0; int next = 0; for(int i = 0; i < num; i++) { next += sc.nextInt(); for(int j = previous; j < next; j++) { a[j] = i; } previous = next; } int worms = sc.nextInt(); for(int i = 0; i < worms; i++) { int pile = sc.nextInt(); System.out.println(a[pile - 1] + 1); } sc.close(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
a97a39b6776fa906619835e0e34ca4ef
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
/** * Simple Array Program * loops practice */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author ganesh */ public class CodeForce474A { public static void main(String[] args) { CodeForce474A data=new CodeForce474A(); data.process(); } void process() { FastScanner sc=new FastScanner(); // Read number of piles int n=sc.nextInt(); int a[]=new int[n]; int count=0; // Read piles for(int i=0;i<n;i++) { count+=sc.nextInt(); a[i]=count; } // read spice number of worms int m=sc.nextInt(); while(m>0) { // read spicy worm label int x=sc.nextInt(); // DO binary search to find number greater than given number System.out.println(binarySearch(x, a,0,a.length)); m--; } } int binarySearch(int x, int a[],int start,int end) { if(end-start==1) { if(a[end]>x &&a[start]<x) { return end+1; } else if(a[end]==x) { return end+1; } else if(a[start]==x) { return start+1; } else if(x<a[start]) { return start+1; } } int mid=(int)(start+end)/2; if(a[mid]<x) { return binarySearch(x,a,mid,end); } else if(a[mid]>x) { return binarySearch(x,a,start,mid); } else { return mid+1; } } } /** * Class TO Read Java Input Faster * * @author ganesh-2564 */ class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
0276ce601fd52c399de6d6e0565de350
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class MainB_2 { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 1; i < n; i++) { a[i] += a[i - 1]; } int m = sc.nextInt(); while (m-- > 0) { int q = sc.nextInt(); System.out.println(upper_bound(a, q)); } } int upper_bound(int a[], int border) { int l = 0; int r = a.length - 1; while (r - l >= 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid + 1; } } return l + 1; } public static void main(String[] args) { new MainB_2().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
c1fae66527ffdeee46925fd35e40a169
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class MainB_2 { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 1; i < n; i++) { a[i] += a[i - 1]; } int m = sc.nextInt(); while (m-- > 0) { int q = sc.nextInt(); System.out.println(lower_bound(a, q) + 1); } } // find minimum i (a[i] >= border) int lower_bound(int a[], int border) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid; } } // r = l + 1 return r; } public static void main(String[] args) { new MainB_2().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
46f42fb6f1846d76fa7a46e39506fd7b
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class MainB_2 { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 1; i < n; i++) { a[i] += a[i - 1]; } int m = sc.nextInt(); while (m-- > 0) { int q = sc.nextInt(); System.out.println(upper_bound(a, q) + 1); } } int upper_bound(int a[], int border) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid; } } return r; } public static void main(String[] args) { new MainB_2().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
1da1833d8783edd3e3ea5e1457a44528
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class MainB { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 1; i < n; i++) { a[i] += a[i - 1]; } int m = sc.nextInt(); for (int i = 0; i < m; i++) { int q = sc.nextInt(); int l = 0; int r = n - 1; int mid = 0; while (r - l >= 1) { mid = (l + r) / 2; if (q <= a[mid]) { r = mid; } else { l = mid + 1; } } System.out.println(r + 1); } } public static void main(String[] args) { new MainB().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
34b1cf937b6039416cbaa6e58ea2b967
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
//################################################################################################################ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; //################################################################################################################ public class R271D2B { public static void main(String[] args) { R271D2B b = new R271D2B(); InputReader1 reader = b.new InputReader1(System.in); OutputWriter writer = b.new OutputWriter(System.out); // put your code here int n = reader.readInt(); int[] csum = new int[n]; csum[0] = reader.readInt(); for (int i = 1; i < csum.length; i++) { csum[i] = csum[i - 1] + reader.readInt(); } int m = reader.readInt(); for (int i = 0; i < m; i++) { int tmp = reader.readInt(); int index = Arrays.binarySearch(csum, tmp); if (index >= 0) { writer.println(index + 1); } else { index = ~index; writer.println(index + 1); } } reader.close(); writer.close(); } class InputReader1 { // private final boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader1(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int readInt() { 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 readLong() { 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 String readString() { int length = readInt(); if (length < 0) return null; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) bytes[i] = (byte) read(); try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { return new String(bytes); } } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public boolean readBoolean() { return readInt() == 1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String s) { writer.println(s); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(long x) { writer.println(x); } public void printSpace() { writer.print(" "); } public void close() { writer.close(); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
20fc94e8e428af2e25c8caec3e6a3487
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF271B { public static void main(final String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] seqNums = new int[n]; for (int i = 0; i < n; i++) { int curr = sc.nextInt(); seqNums[i] = curr + (i > 0 ? seqNums[i - 1] : 0); } int m = sc.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < m; i++) { int worm = sc.nextInt(); int idx = Arrays.binarySearch(seqNums, worm); if (idx >= 0) { sb.append(idx + 1); } else { int possibleIdx = Math.abs(idx + 1); sb.append(possibleIdx + 1); } sb.append("\n"); } System.out.print(sb.toString()); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
4c0ac048f40bfaa90dd8922fdad0346a
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class B { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] piles = new int[n]; for (int i = 0; i < piles.length; i++) { piles[i] = s.nextInt(); } int m = s.nextInt(); int[] juci = new int[m]; for (int i = 0; i < juci.length; i++) { juci[i] = s.nextInt(); } int[] memo = new int[1000000]; int count = 0; for (int i = 0; i < piles.length; i++) { count += piles[i]; for (int j = count - piles[i]; j < count; j++) { memo[j] = i + 1; } } for (int i = 0; i < juci.length; i++) { System.out.println(memo[juci[i]-1]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
4df4d6d4119f8a7e229c84de2704b852
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; public class R271_2_B { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuilder out = new StringBuilder(); int ind, n = in.nextInt(); int[] sum = new int[n+1]; for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { ind = Arrays.binarySearch(sum, in.nextInt()); if (ind < 0) ind = Math.abs(ind) - 1; out.append(ind + "\n"); } System.out.print(out); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
7116ef42680a63cab304b5328268dac2
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; import static java.lang.Math.min; import static java.lang.Math.max; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int qq = 1; //int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int curr = 0; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 1; i <= n; i++) { int k = readInt(); while(k-- > 0) { curr++; map.put(curr, i); } } int qqq = readInt(); while(qqq-- > 0) { pw.println(map.get(readInt())); } } pw.close(); } static class State { public int num, appear; public State(int a, int b) { num = a; appear = b; } } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
bfa055d68a6cd6d0e336c418c2d52710
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] a = new int[n]; int[] result = new int[1000001]; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } int m = s.nextInt(); int[] q = new int[m]; for (int i = 0; i < m; i++) { q[i] = s.nextInt(); } int[] heap = new int[n]; heap[0] = a[0]; for (int i = 1; i < n; i++) { heap[i] = heap[i - 1] + a[i]; } int tmp = 0; for (int i = 1; i <= heap[n-1]; i++) { if (i <= heap[tmp]) { result[i] = tmp + 1; } else { tmp++; result[i] = tmp + 1; } } for (int i :q) { System.out.println(result[i]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
38f42c0d14d94af6a2281572ba5317d6
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Worms { /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int [] array = new int[n]; String [] input = br.readLine().split(" "); for (int i = 0; i < array.length; i++) { int pileCap = Integer.parseInt(input[i]); if (i > 0) { array[i] += array[i - 1]; } if (i < n - 1) { array[i + 1] += pileCap; } } int m = Integer.parseInt(br.readLine()); input = br.readLine().split(" "); for (int i = 0; i < m; i++) { int wormNo = Integer.parseInt(input[i]) - 1; int index = Arrays.binarySearch(array, wormNo); if(index < 0) { index = (index + 1) * -1 - 1; } System.out.println(index + 1); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
b6fbc9efed20fa2bdf55e1d2c9c917ee
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class ProblemB { private static int search(int[] a, int q){ int l = 0, r = a.length - 1; if (q <= a[0]){ return 0; } while (l < r) { int m = (r + l) / 2; if (a[m] < q){ if (a[m + 1] >= q){ return m + 1; } else { l = m + 1; } } else { r = m; } } return - 1; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++){ a[i] = sc.nextInt(); if (i > 0){ a[i] += a[i-1]; } } int m = sc.nextInt(); for (int i = 0; i < m; i++){ int q = sc.nextInt(); System.out.println(search(a, q) + 1); } sc.close(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
32fd90dedd435040dc64cee1cad9d9d5
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static final int INF = Integer.MAX_VALUE / 10; static final double EPS = 1e-10; public static void main(String[] args) { int n = ni(); int[] piles = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { piles[i] = sum += ni(); } int m = ni(); for (int i = 0; i < m; i++) { int target = ni(); out.println(binarySearch(n, piles, target)+1); } out.flush(); } /** * ある命題condition(x)が真となるような最小の解x0を求める二部探索<br> * x∈R,0<=x<=nとする<br> * condition(x)はx0を含む右側で常に真とする */ private static int binarySearch(int n,int[] piles,int target) { //(lb,ub]が解の範囲.初期は(-1,n]=[0,n]となる int lb = -1, ub = n; while (ub - lb > 1) { int mid = (lb + ub) / 2; if (piles[mid]>=target) { //midが条件を満たすとき,解の範囲は(lb,mid] ub = mid; } else { //そうでないなら,(mid,ub] lb = mid; } } return ub; //lb+1=ubとなっている } static int ni() { return in.readInt(); } static long nl() { return in.readLong(); } static String ns() { return in.readString(); } static double nd() { return Double.parseDouble(in.readString()); } static class InputReader { private InputStream stream; private byte[] buf = new byte[102400]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public final 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 final int readInt() { 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 final long readLong() { 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 final 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 final static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
cef861479831ff8a854764ecf80ea1b7
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; /** * * @author hao */ public class Keyboard { static int n,b; static int a[] = new int[100001]; static int sum[] = new int[100001]; /** * @param args the command line arguments */ public static int find(int l,int r,int x) { if (l == r) return l; else if (l==r-1) { if (sum[r] < x) return r; else return l; } else { int mid = (l + r) / 2; if (sum[mid] < x) return find(mid,r,x); else return find(l,mid - 1,x); } } public static void main(String[] args) { Scanner reader = new Scanner(System.in); n = reader.nextInt(); for (int i = 1;i <= n;i++) a[i] = reader.nextInt(); sum[0] = 0; for (int i = 1;i <= n;i++) sum[i] = sum[i - 1] + a[i]; for (int test = reader.nextInt();test > 0;test--) { b = reader.nextInt(); int ans = find(0,n-1,b)+1; System.out.println(ans); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
3b20edaa39c72c7818e0694262cee654
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int array[] = new int[1000010]; int pils = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int pos = 0; for(int i=1; i<=pils;++i){ int size = Integer.parseInt(st.nextToken()); for(int j = pos+1; j<= pos + size;++j){ array[j] = i; } pos = pos + size; } int cons = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); while(cons-->0){ bw.append(array[Integer.parseInt(st.nextToken())] +"\n"); } bw.flush(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
15dbf8a105e02afea2915fe9f3975c46
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Vector; public class aa { public static void main(String[] args) { try{ BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); String input = br.readLine(); int n = Integer.parseInt(input); input = br.readLine(); String [] a1 = input.split(" "); int [] a2 = new int[n]; for(int i=0 ;i<n ;i++) { a2[i] = Integer.parseInt(a1[i]); } input = br.readLine(); int m = Integer.parseInt(input); String[] b1 = br.readLine().split(" "); int [] b2 = new int [m]; for(int i=0 ;i<m;i++) { b2[i]= Integer.parseInt(b1[i]); } int [] ar = new int [1000001]; int x=0; for(int i =0 ;i<n ;i++) { for(int j=x+1 ;j<x+a2[i]+1;j++) ar[j]= i+1; x=x+a2[i]; //System.out.println(x); } for(Integer y:b2) { System.out.println(ar[y]); } //for(int i=0 ;i<26;i++) // System.out.print(i+" "+ar[i]+"#"); } catch(Exception e) { e.printStackTrace(); } }}
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
f73e7c26ac84bec0d8e9b5bfec561258
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; public class maximus { public static void main(String [] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); int array[]=new int [n+1]; int sum=0; for(int i=1;i<=n;i++){ array[i]=in.nextInt(); sum+=array[i]; array[i]=sum; } int temp[]=new int[sum+1]; int ptr=0; for(int i=1;i<=sum;i++){ if(i<=array[ptr]){ temp[i]=ptr; } else if(i>array[ptr]){ ptr++; temp[i]=ptr; } //System.out.println(ptr+" "+i+" "+n+" "+sum); } int m=in.nextInt(); StringBuilder sb=new StringBuilder(); for(int i=0;i<m;i++){ int a=in.nextInt(); sb.append(temp[a]); sb.append('\n'); } System.out.print(sb); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
fc07c8019d59d6943e39b06785f29230
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; import java.io.*; public class wormi{ public static PrintWriter out = new PrintWriter(System.out);//HACER FLUSHHHH public static void main(String args[]) throws IOException{ BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); int cont =Integer.parseInt(lector.readLine()); String tmp[] = lector.readLine().split(" "); int cont2 = Integer.parseInt(lector.readLine()); String tmp2[] = lector.readLine().split(" "); int freq[] = new int[cont]; freq[0]=Integer.parseInt(tmp[0]); //System.out.print(freq[0]+" "); for(int n = 1;n<freq.length;n++){ freq[n]=freq[n-1]+Integer.parseInt(tmp[n]); //System.out.print(freq[n]+" "); } //System.out.println(); StringBuilder sb = new StringBuilder(""); for(int n = 0;n<cont2;n++){ int a = Integer.parseInt(tmp2[n]); int pr = 0; int en = freq.length; while(pr<en){ int med = (pr+en)>>1; if(freq[med]<a) pr = med+1; else en = med; } sb.append((en+1)+"\n"); } System.out.println(sb.substring(0,sb.length()-1)); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
5d8871fc9163a33a4cc1151b3b942fd0
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; import java.util.*; public class Smile { static int binarySearch(int[] array, int n, int key) { int left = 0; int right = n; while (true) { int mid = left + (right - left) / 2; if (mid == 0) { return mid; } else if (key <= array[mid] && key > array[mid - 1]) { return mid; } else if (array[mid] > key) { right = mid; } else left = mid + 1; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 1; i < n; i++) { a[i] = a[i] + a[i - 1]; } int k = in.nextInt(); for (int i = 0; i < k; i++) { int c = in.nextInt(); out.println(binarySearch(a, n - 1, c) + 1); } out.close(); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
e3ef289e0fd18d0b89f6b97c483c3284
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class B271 { public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = toInt(br.readLine()); Long a[] = getLongArray(br.readLine()); int m = toInt(br.readLine()); Long d[] = getLongArray(br.readLine()); long sol[][] = new long[m][3]; for (int i = 0; i < d.length; i++) { sol[i][0] = i; sol[i][1] = d[i]; } Arrays.sort(sol, new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { long t1 = o1[1]; long p1 = o1[0]; long t2 = o2[1]; long p2 = o2[0]; if (t1 == t2) { return (p1 < p2 ? 1 : (p1 == p2 ? 0 : -1)); } else { return (t1 < t2 ? -1 : 1); } } }); // for (int i = 0; i < d.length; i++) { // System.out.println(sol[i][0] + " " + sol[i][1]); // } // System.out.println(""); for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } int j = 0; for (int i = 0; i < a.length; i++) { // System.out.println("a[i] = "+a[i]+" i = "+i); while (j < d.length && sol[j][1] <= a[i]) { //System.out.println("ss "+sol[j][1]); sol[j][2] = i + 1; j++; } } Arrays.sort(sol, new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { long p1 = o1[1]; long t1 = o1[0]; long p2 = o2[1]; long t2 = o2[0]; if (t1 == t2) { return (p1 < p2 ? 1 : (p1 == p2 ? 0 : -1)); } else { return (t1 < t2 ? -1 : 1); } } }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < d.length; i++) { sb.append(sol[i][2] + "\n"); //System.out.println(sol[i][2]); } System.out.println(sb.toString()); // System.out.println(Arrays.toString(a)); } public static void main(String[] args) throws IOException { new B271().solve(); } public static Integer toInt(String s) { return Integer.parseInt(s.trim()); } public static Long toLong(String s) { return Long.parseLong(s.trim()); } public static Double toDouble(String s) { return Double.parseDouble(s.trim()); } public static int[] getIntArray(String line) { String s[] = line.split(" "); int a[] = new int[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Integer.parseInt(s[i]); } return a; } public static Integer[] getIntegerArray(String line) { String s[] = line.split(" "); Integer a[] = new Integer[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Integer.parseInt(s[i]); } return a; } public static Double[] getDoubleArray(String line) { String s[] = line.split(" "); Double a[] = new Double[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Double.parseDouble(s[i]); } return a; } public static Long[] getLongArray(String line) { String s[] = line.split(" "); Long a[] = new Long[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Long.parseLong(s[i]); } return a; } public static Long getMaxFromLongArray(Long a[]) { Long max = Long.MIN_VALUE; for (int i = 0; i < a.length; ++i) { if (max < a[i]) { max = a[i]; } } return max; } public static Long getMinFromLongArray(Long a[]) { Long min = Long.MAX_VALUE; for (int i = 0; i < a.length; ++i) { if (min > a[i]) { min = a[i]; } } return min; } public static Integer getMaxFromIntegerArray(Integer a[]) { Integer max = Integer.MIN_VALUE; for (int i = 0; i < a.length; ++i) { if (max < a[i]) { max = a[i]; } } return max; } public static Integer getMinFromIntegerArray(Integer a[]) { Integer min = Integer.MAX_VALUE; for (int i = 0; i < a.length; ++i) { if (min > a[i]) { min = a[i]; } } return min; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. long res = 1; while (x > 0) { if (x % 2 != 0) { res = (res % p * a % p) % p; } a = (a % p * a % p) % p; x /= 2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod m. //(assuming p is prime). return modPow(a, p - 2, p); } static long modBinomial(long n, long k, long p) { // calculates C(n,k) mod p (assuming p is prime). long numerator = 1; // n * (n-1) * ... * (n-k+1) for (long i = 0; i < k; i++) { numerator = (numerator % p * (n - i) % p) % p; } long denominator = 1; // k! for (long i = 1; i <= k; i++) { denominator = (denominator % p * i % p) % p; } // numerator / denominator mod p. return (numerator % p * modInverse(denominator, p) % p) % p; } public static long calculate(long k, long n) { return (modBinomial(n, k, 1000000007)); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
56e9c1daf232238b64238b595e72c92f
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class BBB { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] ans = new int[(int)1e6+1]; int sum = 0, k = 0; for (int i = 1; i <= n; i++) { int x = sc.nextInt(); sum+=x; for (int j = k; j <= sum; j++) { ans[j] = i; } k = sum+1; } int m = sc.nextInt(); for (int i = 1; i <= m; i++) { System.out.println(ans[sc.nextInt()]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 6
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
226dbf75add210927db4616af9227c1c
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.StreamTokenizer; import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; TokenizerReader in = new TokenizerReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { int[] zFunction(char[] s) { int n = s.length; int[] z = new int[n]; int l = 0, r = 0; for (int i = 1; i < n; ++i) { if (i <= r) z[i] = Math.min(r - i + 1, z[i-l]); while (i + z[i] < n && s[i+z[i]] == s[z[i]]) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } public void solve(@SuppressWarnings("UnusedParameters") int testNumber, TokenizerReader in, PrintWriter out) { String s = in.nextString(); final int n = s.length(); int[] z = zFunction(s.toCharArray()); int maxZ = -1; for (int i = 1; i < n; ++i) { if (z[i] == n-i && maxZ >= n-i) { out.println(s.substring(i)); return; } maxZ = Math.max(maxZ, z[i]); } out.println("Just a legend"); } } class TokenizerReader extends StreamTokenizer { public TokenizerReader(InputStream in) { super(new BufferedReader(new InputStreamReader(in))); defaultConfig(); } public String nextString() { try { nextToken(); } catch (IOException e) { throw new RuntimeException("nextString: exception in line " + lineno(), e); } return sval; } public void defaultConfig() { resetSyntax(); wordChars(33, 126); whitespaceChars(0, ' '); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
f8da3471554f750e612c546e81bfd0b3
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ static int[] z; public static void Z(StringBuilder s){ int L = 0, R = 0; int n = s.length(); z = new int[n]; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s.charAt(R-L) == s.charAt(R)) R++; z[i] = R-L; R--; } else { int k = i-L; if (z[k] < R-i+1) z[i] = z[k]; else { L = i; while (R < n && s.charAt(R-L) == s.charAt(R)) R++; z[i] = R-L; R--; } } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String temp = br.readLine(); StringBuilder s=new StringBuilder(temp); int len=s.length(); Z(s); int max = 0; int i; for ( i = 1; i < len; i++) { if(z[i]==len-i && max>=z[i]){ System.out.println(s.substring(i)); break; } max = Math.max(max, z[i]); } if(i==len||len<3) System.out.println("Just a legend"); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
b90bb9414a31f4ca2a104c07ea2b3d48
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { BufferedReader in; StringTokenizer st; PrintWriter out; void solve() throws IOException { String s = (char) (20) + ns(); int[] z = z(s); int[] p = new int[z.length]; Arrays.fill(p, 0); for (int i = 1; i < p.length; ++i) if (z[i] + i == s.length()) p[z[i]] = z[i]; p[0] = 0; for (int i = 1; i < p.length; ++i) p[i] = max(p[i], p[i - 1]); int best = -1; for (int i = 2; i < s.length() - 1; ++i) { int len = min(z[i], s.length() - i - 1); int cur = min(len, p[len]); if (cur > 0) { if (cur > best) best = cur; } } if (best > 0) { for (int i = 1, j = 0; j < best; ++i, ++j) out.print(s.charAt(i)); out.println(); } else { out.print("Just a legend"); } } private int[] z(String s) { int[] z = new int[s.length()]; int l = 0, r = 0; for (int i = 2; i < s.length(); ++i) { if (i > r) { int j, k; for (j = 1, k = i; k < s.length() && s.charAt(j) == s.charAt(k); ++j, ++k) ; z[i] = j - 1; } else { int w = min(z[i - l + 1], r - i + 1); z[i] = w; if (w == r - i + 1) for (int j = w + 1, k = r + 1; k < s.length() && s.charAt(j) == s.charAt(k); ++j, ++k) ++z[i]; } if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } public Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Main(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
3da1e93d8e25c44d6fe9272497c8726e
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Main { private static void debug(Object... args) { System.out.println(Arrays.deepToString(args)); } public static void main(String[]rags) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int N = s.length(); int[]z = new int[N]; z[0]=N; int lin = 0; int best = 0; int pos = 0; int L = -1, R = -1; for(int i=1;i<N;i++) { if(i > R) { L = R = i; for(int j=i;j<N && s.charAt(j) == s.charAt(j-i);j++) { R++; } z[i] = R - L; R--; } else { int k = z[i - L]; if(k >= R - i + 1) { L = i; for (int j = R; j < N && s.charAt(j) == s.charAt(j - i); j++) { R++; } z[i] = R - L; R--; } else { z[i] = k; } } if(z[i] == N - i) { if(lin >= z[i]) { if(z[i] > best) { best = z[i]; pos = i; } } lin = Math.max(lin, z[i]-1); } else { lin = Math.max(lin, z[i]); } } if(best == 0) System.out.println("Just a legend"); else { System.out.println(s.substring(pos, pos+best)); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
0a7c89dc277a5f1bb5f8a5e7aeb4eab4
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner cin = new Scanner(System.in); StringBuilder cs = new StringBuilder(cin.next()); int len = cs.length(); int cv[] = new int[len]; for (int i = 0; i < len; i++) cv[i] = -1; int f = -1, x = -1; cv[0] = len - 1; for (int i = 1; i < len; i++) { int cd = -1; if (x >= i) { if (cv[i - f] < x - i) { cv[i] = cv[i - f]; continue; } cd = x - i; } f = i; x = cd + i + 1; for (int y = x - f; x < len; x++, y++) if (cs.charAt(x) != cs.charAt(y)) break; cv[i] = --x - i; } // for (int i = 0; i < len; i++) // System.out.print(cv[i] + " "); // System.out.println(); int op[] = new int[len]; for (int i = 1; i < len; i++) { if (cv[i] == -1) continue; int d = cv[i]; op[d] += 2; if (i + d == len - 1) op[d] |= 1; } for (int i = len - 2; i >= 0; i--) op[i] += (op[i + 1] >> 1) << 1; // for (int i = 0; i < len; i++) // System.out.print((op[i] >> 1) + "(" + (op[i] & 1) + ") "); // System.out.println(); int Res = -1; for (int i = len - 1; i >= 0; i--) if ((op[i] & 1) > 0 && (op[i] >> 1) > 1) { Res = i; break; } System.out.println(Res > -1 ? cs.substring(0, Res + 1) : "Just a legend"); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
1360a161ab15272f2c1d1e0b31ad8022
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.lang.*; import java.awt.geom.Line2D; import java.io.*; import java.util.*; import java.math.*; public class B implements Runnable{ public int[] pf(String str) { char[] s = str.toCharArray(); int[] p = new int[s.length]; int n = s.length; p[0] = 0; for (int i = 1; i < n; ++i) { int j = p[i-1]; while (j > 0 && s[i] != s[j]) { j = p[j-1]; } if (s[i] == s[j]) { ++j; } p[i] = j; } return p; } public void run() { String str = nextLine(); int[] p1 = pf(str); int maxLength = 0; HashSet<Integer> h = new HashSet<Integer>(); long pow = 1L; long h1 = 0; long h2 = 0; for (int i = 0; i < str.length()-1; ++i) { h1 *= 31L; h1 += (int)(str.charAt(i) - 'a'); h2 += pow*(int)(str.charAt(str.length()-i-1) - 'a'); pow *= 31L; if (h1 == h2) { h.add(i+1); } } for (int i = 1; i < str.length()-1; ++i) { if (p1[i] > 0 && h.contains(p1[i])) { maxLength = Math.max(maxLength, p1[i]); } } if (maxLength == 0) { out.println("Just a legend"); } else { for (int i = 0; i < maxLength; ++i) { out.print(str.charAt(i)); } out.println(); } out.flush(); } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new B())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
1d67c98f0987b1593728a1b63b40d0f7
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ void solve() throws IOException { String s = in.readLine(); int len = s.length(); char[] ss = s.toCharArray(); int[] pi = piFunction(ss); int[] z = zFunction(ss); boolean[] good = new boolean [len]; for (int i = 1; i < len; i++) { if (i + z[i] == len) { good[z[i]] = true; } } // System.err.println(Arrays.toString(pi)); // System.err.println(Arrays.toString(z)); int max = 0; for (int i = 1; i < len - 1; i++) { if (good[pi[i]]) { max = max(max, pi[i]); } } out.println(max == 0 ? "Just a legend" : s.subSequence(0, max)); } int[] piFunction(char[] s) { int n = s.length; int[] pi = new int [n]; for (int i = 1, j; i < n; pi[i] = s[i] == s[j] ? j + 1 : j, i++) for (j = pi[i - 1]; j > 0 && s[i] != s[j]; j = pi[j - 1]); return pi; } int[] zFunction(char[] s) { int n = s.length; int[] z = new int [n]; for (int i = 1, l = 0, r = 0; i < n; i++) { if (i <= r) z[i] = min(r - i + 1, z[i - l]); while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
bba4f412b587644d38f155266fe88b24
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ void solve() throws IOException { String s = in.readLine(); int len = s.length(); char[] ss = s.toCharArray(); int[] pi = piFunction(ss); int[] z = zFunction(ss); boolean[] good = new boolean [len]; for (int i = 1; i < len; i++) { if (i + z[i] == len) { good[z[i]] = true; } } // System.err.println(Arrays.toString(pi)); // System.err.println(Arrays.toString(z)); int max = 0; for (int i = 1; i < len - 1; i++) { if (good[pi[i]]) { max = max(max, pi[i]); } } out.println(max == 0 ? "Just a legend" : s.subSequence(0, max)); } int[] piFunction(char[] s) { int n = s.length; int[] pi = new int [n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; pi[i] = j + (s[i] == s[j] ? 1 : 0); } return pi; } int[] zFunction(char[] s) { int len = s.length; int[] z = new int [len]; int l = 0; int r = 0; for (int i = 1, j; i < len; i++) if (i > r) { for (j = 0; i + j < len && s[j] == s[i + j]; j++); z[i] = j; l = i; r = i + j - 1; } else { if (z[i - l] < r - i + 1) { z[i] = z[i - l]; } else { for (j = 1; r + j < len && s[r + j] == s[r - i + j]; j++); z[i] = r - i + j; l = i; r = r + j - 1; } } return z; } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
bde3ca4025aee1ff8c02b4651a1ac28c
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class Contest_93_B { static int[] fail; public static void Zfunction (String s) { fail=new int[s.length()]; int l = 0, r = 0; for (int i=1; i<s.length(); ++i) if (fail[i-l]+i <= r) fail[i] = fail[i-l]; else { l = i; if (i > r) r = i; for (fail[i] = r-i; r<s.length(); ++r, ++fail[i]) if (s.charAt(r) != s.charAt(fail[i])) break; --r; } } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); if (s.length() < 3) { System.out.println("Just a legend"); return; } fail = new int[s.length()]; Zfunction(s); int max = 0; int index = -1; for (int i = 1; i < fail.length; i++) { if(fail[i]==s.length()-i && max>=fail[i]){ index = i; break; } max = Math.max(max, fail[i]); } if(index==-1) System.out.println("Just a legend"); else System.out.println(s.substring(index)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
4244bbbad9ceda3151be671b8d8dd398
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class Contest_93_B { static int[] z; public static int[] Zfunction3(String n) { z = new int[n.length()]; for (int i = 1, l = 0, r = 0; i < n.length(); ++i) { if (i <= r) { z[i] = Math.min(r - i + 1, z[i - l]); // if z[i-1] smaller than right limit or more than right limit // then z[i] = min(r-i+1,z[i-1]) but if it's equal we need more // comparisons if (z[i - l] != r - i + 1) continue; } while (i + z[i] < n.length() && n.charAt(z[i]) == n.charAt(i + z[i])) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); if (s.length() < 3) { System.out.println("Just a legend"); return; } Zfunction3(s); int max = 0; int index = -1; for (int i = 1; i < z.length; i++) { if(z[i]==s.length()-i && max>=z[i]){ index = i; break; } max = Math.max(max, z[i]); } if(index==-1) System.out.println("Just a legend"); else System.out.println(s.substring(index)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
c4f608453da7e431ea9aca334a24cd56
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; public class Main { BufferedReader in; PrintStream out; StringTokenizer tok; Scanner sc; public Main() throws NumberFormatException, IOException { //sc = new Scanner(System.in); //sc = new Scanner(new FileReader("in.txt")); in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { String s = nextToken(); int[] zfun = ZFunction(s); int len = zfun.length; int mid = 0; int end = 0; for(int i = 1; i < len; i++) { int v = zfun[i]; if(v + i == len) mid = Math.max(mid, v-1); else mid = Math.max(mid, v); } for(int i = 1; i < len; i++) { int v = zfun[i]; if(v + i == len && v <= mid) end = Math.max(end, v); } if(end == 0)out.print("Just a legend"); else for(int i = len-end; i < len; i++)out.print(s.charAt(i)); } int[] ZFunction(String s) { int len=s.length(); int[] resp = new int[len]; int l = 1, r = -1; int k = 0; for (int i = 1; i < len; i++) { k = 0; if (i < r) k = Math.min(r - i + 1, resp[i - l]); while (i + k <len && s.charAt(i + k) == s.charAt(k)) k++; resp[i] = k--; if (i + k > r) { l = i; r = i + k; } } return resp; } public static void main(String[] args) throws NumberFormatException, IOException { new Main(); } String nextToken() throws IOException { String line = ""; if (tok == null || !tok.hasMoreTokens()) { if ((line = in.readLine()) != null) tok = new StringTokenizer(line); else return null; } return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
ffcb6b830a5a054e80b8ed284f66e515
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; public class Codeforces_Password { public static int[] prefixFunction(String s) { int n = s.length(); int[] p = new int[n]; for (int i = 1; i < n; i++) { int k = p[i - 1]; while (k > 0 && s.charAt(k) != s.charAt(i)) k = p[k - 1]; p[i] = k + (s.charAt(k) == s.charAt(i) ? 1 : 0); } return p; } public static void main(String[] args)throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int[] pf = prefixFunction(s); int l = pf.length-1; int P = pf[l]; int pi = 0; if(P > 0) pi = pf[P-1]; int sol = 0; for(int i = l-1; i >= 0 ; i--) if(pf[i] == P || pf[i] == pi) sol = Math.max(sol, pf[i]); if(sol > 0) { for(int i = 0; i < sol; i++) System.out.print(s.charAt(i)); } else System.out.print("Just a legend"); System.out.println(""); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
a21a32c5ed3582700c5e91625eca144f
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class BetaRound93_Div1_B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound93_Div1_B(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution final long PRIME1 = 31; final long PRIME2 = 57; int n; char[] s; long[] h1, h2, p1, p2; long hash1(int L, int R) { return (L == 0) ? h1[R] : h1[R] - h1[L-1]; } long hash2(int L, int R) { return (L == 0) ? h2[R] : h2[R] - h2[L-1]; } void solve() throws IOException { s = readString().toCharArray(); n = s.length; p1 = new long[n+1]; p1[0] = 1; for (int i = 1; i <= n; i++) { p1[i] = p1[i-1] * PRIME1; } p2 = new long[n+1]; p2[0] = 1; for (int i = 1; i <= n; i++) { p2[i] = p2[i-1] * PRIME2; } h1 = new long[n]; h1[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h1[i] = h1[i-1] + p1[i] * (s[i] - 'a' + 1); } h2 = new long[n]; h2[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h2[i] = h2[i-1] + p2[i] * (s[i] - 'a' + 1); } int[] lengths = new int[n]; int size = 0; for (int len = 1; len <= n-2; len++) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] == suffixHash1 && prefixHash2 * p2[n-len] == suffixHash2) { lengths[size++] = len; } } int L = 0, R = size - 1, mid = -1, pos = -1, ans = -1; while (L < R) { mid = (L + R) / 2; int len = lengths[mid]; int res = check(len); if (res >= 0) { L = mid + 1; if (len > ans) { pos = res; ans = len; } } else { R = mid; } } for (int i = max(0, L-20); i <= min(size-1, R+20); i++) { int len = lengths[i]; int res = check(len); if (res >= 0) { if (len > ans) { pos = res; ans = len; } } } if (pos == -1) { out.println("Just a legend"); return; } for (int i = pos; i < pos + ans; i++) { out.print(s[i]); } out.println(); } int check(int len) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] != suffixHash1 || prefixHash2 * p2[n-len] != suffixHash2) { return -1; } for (int start = 1; start + len < n; start++) { long h1 = hash1(start, start+len-1); long h2 = hash2(start, start+len-1); if (h1 == prefixHash1 * p1[start] && h2 == prefixHash2 * p2[start]) { return start; } } return -1; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
9148c5a99094b086214135cc987aaca3
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class BetaRound93_Div1_B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound93_Div1_B(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution final long PRIME1 = 31; final long PRIME2 = 57; int n; char[] s; long[] h1, h2, p1, p2; long hash1(int L, int R) { return (L == 0) ? h1[R] : h1[R] - h1[L-1]; } long hash2(int L, int R) { return (L == 0) ? h2[R] : h2[R] - h2[L-1]; } void solve() throws IOException { s = readString().toCharArray(); n = s.length; p1 = new long[n+1]; p1[0] = 1; for (int i = 1; i <= n; i++) { p1[i] = p1[i-1] * PRIME1; } p2 = new long[n+1]; p2[0] = 1; for (int i = 1; i <= n; i++) { p2[i] = p2[i-1] * PRIME2; } h1 = new long[n]; h1[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h1[i] = h1[i-1] + p1[i] * (s[i] - 'a' + 1); } h2 = new long[n]; h2[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h2[i] = h2[i-1] + p2[i] * (s[i] - 'a' + 1); } int[] lengths = new int[n]; int size = 0; for (int len = 1; len <= n-2; len++) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] == suffixHash1 && prefixHash2 * p2[n-len] == suffixHash2) { lengths[size++] = len; } } int L = 0, R = size - 1, mid = -1, pos = -1, ans = -1; while (L < R) { mid = (L + R) / 2; int len = lengths[mid]; int res = check(len); if (res >= 0) { L = mid + 1; if (len > ans) { pos = res; ans = len; } } else { R = mid; } } for (int i = max(0, L-20); i <= min(size-1, R+20); i++) { int len = lengths[i]; int res = check(len); if (res >= 0) { if (len > ans) { pos = res; ans = len; } } } if (pos == -1) { out.println("Just a legend"); return; } for (int i = pos; i < pos + ans; i++) { out.print(s[i]); } out.println(); } int check(int len) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] != suffixHash1 && prefixHash2 * p2[n-len] != suffixHash2) { return -1; } for (int start = 1; start + len < n; start++) { long h1 = hash1(start, start+len-1); long h2 = hash2(start, start+len-1); if (h1 == prefixHash1 * p1[start] && h2 == prefixHash2 * p2[start]) { return start; } } return -1; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
73a561a688fc3833494c0be3dddf18b0
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class BetaRound93_Div1_B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound93_Div1_B(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution final long PRIME1 = 31; final long PRIME2 = 57; int n; char[] s; long[] h1, h2, p1, p2; long hash1(int L, int R) { return (L == 0) ? h1[R] : h1[R] - h1[L-1]; } long hash2(int L, int R) { return (L == 0) ? h2[R] : h2[R] - h2[L-1]; } void solve() throws IOException { s = readString().toCharArray(); n = s.length; p1 = new long[n+1]; p1[0] = 1; for (int i = 1; i <= n; i++) { p1[i] = p1[i-1] * PRIME1; } p2 = new long[n+1]; p2[0] = 1; for (int i = 1; i <= n; i++) { p2[i] = p2[i-1] * PRIME2; } h1 = new long[n]; h1[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h1[i] = h1[i-1] + p1[i] * (s[i] - 'a' + 1); } h2 = new long[n]; h2[0] = s[0] - 'a' + 1; for (int i = 1; i < n; i++) { h2[i] = h2[i-1] + p2[i] * (s[i] - 'a' + 1); } int[] lengths = new int[n]; int size = 0; for (int len = 1; len <= n-2; len++) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] == suffixHash1 && prefixHash2 * p2[n-len] == suffixHash2) { lengths[size++] = len; } } int L = 0, R = size - 1, mid = -1, pos = -1, ans = -1; while (L < R) { mid = (L + R) / 2; int len = lengths[mid]; int res = check(len); if (res >= 0) { L = mid + 1; if (len > ans) { pos = res; ans = len; } } else { R = mid; } } for (int i = max(0, L-1); i <= min(size-1, R+1); i++) { int len = lengths[i]; int res = check(len); if (res >= 0) { if (len > ans) { pos = res; ans = len; } } } if (pos == -1) { out.println("Just a legend"); return; } for (int i = pos; i < pos + ans; i++) { out.print(s[i]); } out.println(); } int check(int len) { long prefixHash1 = hash1(0, len-1); long suffixHash1 = hash1(n-len, n-1); long prefixHash2 = hash2(0, len-1); long suffixHash2 = hash2(n-len, n-1); if (prefixHash1 * p1[n-len] != suffixHash1 || prefixHash2 * p2[n-len] != suffixHash2) { return -1; } for (int start = 1; start + len < n; start++) { long h1 = hash1(start, start+len-1); long h2 = hash2(start, start+len-1); if (h1 == prefixHash1 * p1[start] && h2 == prefixHash2 * p2[start]) { return start; } } return -1; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
3987caca6f68ccf4f16fe05a7b1a8f50
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.TreeSet; public class B { private static int[] prfunc (char[] s) { int n = s.length; int[] ans = new int[n]; for (int i=1; i<n; i++) { int j = ans[i-1]; while (j > 0 && s[i] != s[j]) j = ans[j-1]; if (s[i] == s[j]) j++; ans[i] = j; } return ans; } public static void main(String[] args)throws Exception { String s = inB.readLine(); char[] c = s.toCharArray(); int n = s.length(); int[] pf = prfunc(c); /* for(int i = 0; i<n; i++) { while(pf[i]*2 > i+1) { pf[i] = pf[i]*2 - (i+1); } }/**/ /* for(int i = 0; i<pf.length; i++) { out.print(pf[i] + " "); } out.println(); out.flush();/**/ TreeSet<Integer> ts = new TreeSet<Integer>(); for(int i = 1; i<n-1; i++) { if(pf[i]!=0)ts.add(pf[i]); } if(pf[n-1] == 0) { exit("Just a legend"); } /* Integer ii = ts.floor(pf[n-1]); if(ii == null) { exit("Just a legend"); } println(s.substring(0, ii));/**/ int cur = n-1; for(;;) { if(pf[cur] == 0)break; if(ts.contains(pf[cur])) { exit(s.substring(0, pf[cur])); } cur = pf[cur]-1; } exit("Just a legend"); } ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=false; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
4e79037d5644fac5045f22320d34d9ac
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { char[] s = in.next().toCharArray(); int[] z = zAlgo(s); int max = 0; int ind = 0; boolean f = false; for (int i = 1; i < s.length; i++) { if (z[i] == s.length - i && max >= z[i]) { ind = i; f = true; break; } max = Math.max(max, z[i]); } if (!f) { System.out.println("Just a legend"); } else { for (int i = ind; i < s.length; i++) { System.out.print(s[i]); } System.out.println(); } } } public static int[] zAlgo(char[] s) { int n = s.length; int[] z = new int[n]; int R = 0, L = 0; for (int i = 1; i < n; i++) { if (i > R) { R = L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) { z[i] = z[k]; } else { L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } } return z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
dd0dc4d61dfb381f004388c17e6fb4e0
train_002.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class round93B { static char[] Text, Pattern; static int[] back; static int n, m; static ArrayList<Integer> occurrences; static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } public static long[] hash(char[] sequence) { long seed = 131; long hash_code = sequence[0]; long[] hash = new long[sequence.length]; hash[0] = sequence[0]; for (int i = 1; i < sequence.length; ++i) { hash_code = (hash_code * seed) + sequence[i]; hash[i] = hash_code; } return hash; } public static long[] reverseHash(char[] sequence) { long seed = 131; long hash_code = sequence[0]; long[] reverse_hash = new long[sequence.length]; reverse_hash[0] = sequence[0]; long po = seed; for (int i = 1; i < sequence.length; ++i) { hash_code = (hash_code + po * sequence[i]); reverse_hash[i] = hash_code; po = po * seed; } return reverse_hash; } public static String reverse(char[] s) { StringBuffer ans = new StringBuffer(); for (int i = s.length - 1; i >= 0; --i) ans.append(s[i]); return ans.toString(); } // processes the pattern being searched for. public static void kmpPreprocess() { int i = 0, j = -1; back[0] = -1; while (i < m) { while (j >= 0 && Pattern[i] != Pattern[j]) j = back[j]; ++i; ++j; back[i] = j; } } // does the search public static void kmpSearch() { int i = 0, j = 0; while (i < n) { while (j >= 0 && Text[i] != Pattern[j]) j = back[j]; ++i; ++j; if (j == m) { occurrences.add(i - j); j = back[j]; } } } public static void main(String[] args) throws Exception { char[] s = next().toCharArray(); long[] hash = hash(s); long[] rev_hash = reverseHash((reverse(s).toCharArray())); Text = s; n = Text.length; for (int i = hash.length - 1; i >= 0; --i) { if (hash[i] == rev_hash[i] && i != hash.length - 1) { Pattern = new char[i + 1]; for (int j = 0; j <= i; ++j) Pattern[j] = s[j]; m = Pattern.length; back = new int[m + 1]; occurrences = new ArrayList<Integer>(); kmpPreprocess(); kmpSearch(); for (int j = 0; j < occurrences.size(); ++j) { int cur = occurrences.get(j); if (cur != 0 && cur + i < s.length - 1) { System.out.println(new String(Pattern)); return; } } } } System.out.println("Just a legend"); return; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 6
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
23d30d1879e6b6f957b321fb85958820
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; 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(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); HashMap<Long, Long> map = new HashMap<>(); long totVal = (1L << k) - 1L; long a[] = new long[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextLong(); long sum = 0; long rem = 0; map.put(0L, 1L); for(int i = 0; i < n; ++i) { sum ^= a[i]; if(map.get(sum) == null) map.put(sum, 1L); else map.put(sum, map.get(sum) + 1L); long val2 = sum ^ totVal; if(map.get(val2) == null) map.put(val2, 1L); else map.put(val2, map.get(val2) + 1L); } for(long i : map.keySet()) { long newVal = i ^ totVal; if(newVal < i) continue; long cnt1 = map.get(i) / 2L; long cnt2 = map.get(i) - cnt1; rem += cnt1 * (cnt1 - 1L) / 2L; rem += cnt2 * (cnt2 - 1L) / 2L; } long ans = n * (n + 1L) / 2L - rem; w.print(ans); w.close(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
b747ffa9d22500fdd89892359066410f
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; 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(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); HashMap<Long, Long> map = new HashMap<>(); long totVal = (1L << k) - 1L; long a[] = new long[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextLong(); long sum = 0; long rem = 0; map.put(0L, 1L); for(int i = 0; i < n; ++i) { long cnt0 = 0, cntFull = 0; sum ^= a[i]; if(map.get(sum) != null) cnt0 = map.get(sum); if(map.get(sum ^ totVal) != null) cntFull = map.get(sum ^ totVal); if(cnt0 > cntFull) sum ^= totVal; rem += min(cnt0, cntFull); if(map.get(sum) == null) map.put(sum, 1L); else map.put(sum, map.get(sum) + 1L); } long ans = n * (n + 1L) / 2L - rem; w.print(ans); w.close(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
fecc6a45cafcb567af4d2100b25551cd
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
//package mailru2018; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), K = ni(); int[] a = na(n); int[] cum = new int[n+1]; for(int i = 0;i < n;i++){ cum[i+1] = cum[i] ^ a[i]; } cum = radixSort(cum); int[][] uc = uniqcount(cum); int j = uc.length-1; long ans = 0; for(int i = 0;i < uc.length;i++){ long num = uc[i][1]; ans += num*(num-1)/2 - (num/2)*(num-num/2); } for(int i = 0;i < j;i++){ while(i < j && uc[i][0]+uc[j][0] >= 1<<K){ j--; } if(i < j){ if(uc[i][0]+uc[j][0] == (1<<K)-1){ { long num = uc[i][1] + uc[j][1]; ans += num*(num-1)/2 - (num/2)*(num-num/2); } { long num = uc[i][1]; ans -= num*(num-1)/2 - (num/2)*(num-num/2); } { long num = uc[j][1]; ans -= num*(num-1)/2 - (num/2)*(num-num/2); } j--; } } } out.println((long)n*(n+1)/2 - ans); } public static int[][] uniqcount(int[] a) { int n = a.length; int p = 0; int[][] b = new int[n][]; for(int i = 0;i < n;i++){ if(i == 0 || a[i] != a[i-1])b[p++] = new int[]{a[i], 0}; b[p-1][1]++; } return Arrays.copyOf(b, p); } public static int[] radixSort(int[] f){ return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } 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(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
2728f8e0b10c68ff1ebb79f9854bd1a9
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ public class cf4 implements Runnable{ static void addMap(HashMap<Integer, Integer> hm, int x) { if(hm.get(x) != null) hm.put(x, hm.get(x) + 1); else hm.put(x, 1); } static void subMap(HashMap<Integer, Integer> hm, int x) { if(hm.get(x) != null) hm.put(x, hm.get(x) - 1); else hm.put(x, -1); } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(), k = s.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = s.nextInt(); int[] pre = new int[n]; pre[0] = a[0]; for(int i = 1; i < n; i++) pre[i] = pre[i - 1] ^ a[i]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i = 0; i < n; i++) addMap(hm, pre[i]); long res = 0; for(Map.Entry<Integer, Integer> e : hm.entrySet()) { //w.println(e.getKey() + " " + e.getValue()); if(e.getKey() == 0) res += e.getValue(); res += (long)e.getValue() * (e.getValue() - 1) / 2; } //w.println((long)n * (n + 1) / 2 - res); int mask = ((1 << k) - 1); for(int i = n - 1; i >= 0; i--) { int c = 0; //w.println(pre[i]); if(hm.get(pre[i] ^ mask) != null) c = hm.get(pre[i] ^ mask); int add = 0; if(pre[i] == 0) add = 1; if(c + 1 <= hm.get(pre[i]) - 1 + add) { subMap(hm, pre[i]); a[i] ^= mask; pre[i] ^= mask; addMap(hm, pre[i]); } } res = 0; for(Map.Entry<Integer, Integer> e : hm.entrySet()) { //w.println(e.getKey() + " " + e.getValue()); if(e.getKey() == 0) res += e.getValue(); res += (long)e.getValue() * (e.getValue() - 1) / 2; } w.println((long)n * (n + 1) / 2 - res); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 cf4(),"cf4",1<<26).start(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
829756bb7b4c9f201df82f9198c708e8
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; public class D implements Runnable { public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(); int k = fs.nextInt(); int AND = (1 << k) - 1; int[] a = fs.nextIntArray(n); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int curXOR = 0; long res = 0; add(map, 0); for(int i = 0; i < n; i++) { curXOR ^= a[i]; int numRanges = i + 1; if(a[i] == 0) numRanges--; if(map.containsKey(curXOR)) numRanges -= map.get(curXOR); //but what if i flip? curXOR ^= a[i]; int gets = flip(a[i], AND); curXOR ^= gets; int numRanges2 = i + 1; if(gets == 0) numRanges2--; if(map.containsKey(curXOR)) numRanges2 -= map.get(curXOR); if(numRanges2 > numRanges) { //yeah flip res += numRanges2; add(map, curXOR); } else { //nah curXOR ^= gets; curXOR ^= a[i]; add(map, curXOR); res += numRanges; } } out.println(res); out.close(); } private void add(HashMap<Integer, Integer> map, int curXOR) { if(!map.containsKey(curXOR)) map.put(curXOR, 0); map.put(curXOR, map.get(curXOR)+1); } int flip(int a, int b) { int res = ~a; res &= b; return res; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
c312eaf37a9c2dafb82f781de86368c1
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DChangingArray solver = new DChangingArray(); solver.solve(1, in, out); out.close(); } static class DChangingArray { HashMap<Integer, Integer> mp; int n; int k; public long c2(long n) { return n * (n - 1) / 2 + n; } void add(int num) { if (((num >> (k - 1)) & 1) == 1) num ^= (1 << k) - 1; Integer g = mp.get(num); if (g == null) g = 0; mp.put(num, g + 1); } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); k = in.nextInt(); int[] arr = in.readIntArray(n); mp = new HashMap<>(); long ans = c2(n); mp.put(0, 1); add(arr[0]); for (int i = 1; i < n; i++) { arr[i] ^= arr[i - 1]; add(arr[i]); } for (int x : mp.values()) { ans -= c2(x / 2) + c2(x - x / 2) - x; } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
e4a80a4274648adbb7a763e716aacbb7
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class D { void submit() { int n = nextInt(); int k = nextInt(); int[] a = new int[n + 1]; for (int i = 0; i < n; i++) { a[i + 1] = a[i] ^ nextInt(); } int y = (1 << k) - 1; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i <= n; i++) { int x = a[i]; if (x > y - x) { x = y - x; } map.merge(x, 1, Integer::sum); } long ans = (long)n * (n + 1) / 2; for (int x : map.values()) { int half = x / 2; ans -= (long)half * (half - 1) / 2 + (long)(x - half) * (x - half - 1) / 2; } out.println(ans); } void test() { } void stress() { for (int tst = 0;; tst++) { if (false) { throw new AssertionError(); } System.err.println(tst); } } D() throws IOException { is = System.in; out = new PrintWriter(System.out); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static final int C = 5; static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new D(); } private InputStream is; PrintWriter out; private byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() { long ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
3e1c5f2a9ec31c492dbb0c5a4016c22c
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.Map.Entry; public class Main { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private PrintWriter pw; private long mod = 1000000000 + 7; private StringBuilder ans_sb; private void soln() { long n = nextInt(); int k = nextInt(); int max = (int) Math.pow(2, k) - 1; // debug(max); HashMap<Integer, Long> map = new HashMap<>(); map.put(0, 1L); long cnt = (n * (n + 1)) / 2; boolean f = false; int xor = 0; for (int i = 0; i < n; i++) { int x = nextInt(); if (f) { x = max - x; } // debug(x); int xp = max - x; // debug(xp); x = x ^ xor; xp = xp ^ xor; long c1 = 0; long c2 = 0; if (map.containsKey(x)) { c1 = map.get(x); } if (map.containsKey(xp)) c2 = map.get(xp); if (c2 < c1) { f = !f; xor = xp; map.put(xor, c2 + 1); } else { xor = x; map.put(xor, c1 + 1); } // debug(xor); cnt -= Math.min(c1, c2); // debug(cnt); } pw.println(cnt); } private void recur(int st, int et, int lv, int rv, int nv, int[] l, int[] r, int[] na) { debug(st + " " + et + " " + lv + " " + rv); if (et < st) return; int cnt = 0; for (int i = st; i <= et; i++) { if (l[i] == lv && r[i] == rv) { na[i] = nv; cnt++; } } int c = 0; int prev = st - 1; for (int i = st; i <= et; i++) { if (l[i] == lv && r[i] == rv) { // debug(i); recur(prev + 1, i - 1, lv + c, rv + cnt - c, nv - 1, l, r, na); prev = i; c++; } } recur(prev + 1, et, lv + c, rv + cnt - c, nv - 1, l, r, na); } private String solveEqn(long a, long b) { long x = 0, y = 1, lastx = 1, lasty = 0, temp; while (b != 0) { long q = a / b; long r = a % b; a = b; b = r; temp = x; x = lastx - q * x; lastx = temp; temp = y; y = lasty - q * y; lasty = temp; } return lastx + " " + lasty; } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } private long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { @Override public void run() { new Main().solve(); } }, "1", 1 << 26).start(); // new Main().solve(); } public StringBuilder solve() { InputReader(System.in); /* * try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt")); * } catch(FileNotFoundException e) {} */ pw = new PrintWriter(System.out); // ans_sb = new StringBuilder(); soln(); pw.close(); // System.out.println(ans_sb); return ans_sb; } public void InputReader(InputStream stream1) { stream = stream1; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private 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++]; } private 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; } private 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; } private String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private 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(); } private int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); char c1 = (char) c; while (!isSpaceChar(c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
be4476c2c11674381bc8ccce63dea3d7
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; public class D implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! @SuppressWarnings("unused") private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int k = readInt(); int[] a = readIntArray(n); long answer = getSmartAnswer(n, k, a); out.println(answer); } long getSmartAnswer(int n, int k, int[] a) { int high = (1 << k) - 1; Map<Integer, Integer> prefixes = new HashMap<>(); { int prefix = 0; prefixes.put(prefix, 1); for (int first : a) { int second = high - first; prefix = min(prefix ^ first, prefix ^ second); prefixes.put(prefix, prefixes.getOrDefault(prefix, 0) + 1); } } long answer = (long)n * (n + 1) / 2; for (Map.Entry<Integer, Integer> entry : prefixes.entrySet()) { int size = entry.getValue(); int firstSize = size / 2, secondSize = size - firstSize; long firstCount = (long)firstSize * (firstSize - 1) / 2; long secondCount = (long)secondSize * (secondSize - 1) / 2; answer -= firstCount + secondCount; } return answer; } long getAnswer(int n, int k, int[] a) { int high = (1 << k) - 1; Map<Integer, Integer> prefixes = new HashMap<>(); int prefix = 0; prefixes.put(prefix, 1); long answer = 0; for (int i = 0; i < n; ++i) { int value = a[i]; int first = value, second = high - first; int firstPrefix = prefix ^ first, secondPrefix = prefix ^ second; int firstCount = prefixes.getOrDefault(firstPrefix, 0); int secondCount = prefixes.getOrDefault(secondPrefix, 0); if (firstCount < secondCount) { prefixes.put(firstPrefix, firstCount + 1); prefix = firstPrefix; } else { prefixes.put(secondPrefix, secondCount + 1); prefix = secondPrefix; } answer += (i + 1) - min(firstCount, secondCount); } return answer; } long getBruteAnswer(int n, int k, int[] a, long check) { int high = (1 << k) - 1; long answer = -1; for (int mask = 0; mask < (1 << n); ++mask) { for (int bit = 0; bit < n; ++bit) { if (checkBit(mask, bit)) { a[bit] = high - a[bit]; } } Map<Integer, Integer> prefixes = new HashMap<>(); int prefix = 0; prefixes.put(prefix, 1); long result = 0; for (int i = 0; i < n; ++i) { int value = a[i]; prefix ^= value; int count = prefixes.getOrDefault(prefix, 0); prefixes.put(prefix, count + 1); result += (i + 1) - count; } for (int bit = 0; bit < n; ++bit) { if (checkBit(mask, bit)) { a[bit] = high - a[bit]; } } if (answer < result) { answer = result; } if (answer == result && result == check) { out.println(mask); } } return answer; } ///////////////////////////////////////////////////////////////////// private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long inverse(long x) { return binpow(x, MODULO - 2); } private static long binpow(long base, long power) { if (power == 0) return 1; if ((power & 1) == 0) { long half = binpow(base, power >> 1); return mult(half, half); } else { long prev = binpow(base, power - 1); return mult(prev, base); } } private static long add(long a, long b) { return (a + b) % MODULO; } @SuppressWarnings("unused") private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") void yesNo(boolean yes) { out.println(yes ? "YES" : "NO"); } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException | EOFException e) { break; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new D(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @SuppressWarnings("unused") private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readNullableLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readLine() { String line = readNullableLine(); if (null == line) throw new EOFException(); return line; } private String readString() { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; @SuppressWarnings("unused") private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } @SuppressWarnings("unused") private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } @SuppressWarnings("unused") private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } @SuppressWarnings("unused") private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } @SuppressWarnings("unused") private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } @SuppressWarnings("unused") private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private BigInteger readBigInteger() { return new BigInteger(readString()); } @SuppressWarnings("unused") private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } @SuppressWarnings("unused") private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated @SuppressWarnings("unused") private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { @SuppressWarnings("unchecked") List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } @SuppressWarnings("unused") private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; @SuppressWarnings("unused") private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } @SuppressWarnings("unused") private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { @SuppressWarnings("unused") static Comparator<IntIndexPair> increaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static Comparator<IntIndexPair> decreaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } @SuppressWarnings("unused") int getRealIndex() { return index + 1; } } @SuppressWarnings("unused") private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @SuppressWarnings("unused") void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class EOFException extends RuntimeException { EOFException() { super(); } } private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static void swap(int[] array, int i, int j) { if (i != j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static <T> void swap(T[] array, int i, int j) { if (i != j) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; @SuppressWarnings("unused") private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } @SuppressWarnings("unused") private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } @SuppressWarnings("unused") private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } @SuppressWarnings("unused") private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } @SuppressWarnings("unused") long[] getDivisors(long value) { List<Long> divisors = new ArrayList<>(); for (long divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castLong(divisors); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } @SuppressWarnings("unused") private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ @SuppressWarnings("unused") private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } @SuppressWarnings("unused") private static List<Integer> shuffled(List<Integer> list) { Collections.shuffle(list, rnd); return list; } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
6cceda67f97115c7a3cb681924ef38d9
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; public class D implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! @SuppressWarnings("unused") private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int k = readInt(); int[] a = readIntArray(n); long answer = getAnswer(n, k, a); out.println(answer); } long getAnswer(int n, int k, int[] a) { int high = (1 << k) - 1; Map<Integer, Integer> prefixes = new HashMap<>(); int prefix = 0; prefixes.put(prefix, 1); long answer = 0; for (int i = 0; i < n; ++i) { int value = a[i]; int first = value, second = high - first; int firstPrefix = prefix ^ first, secondPrefix = prefix ^ second; int firstCount = prefixes.getOrDefault(firstPrefix, 0); int secondCount = prefixes.getOrDefault(secondPrefix, 0); if (firstCount < secondCount) { prefixes.put(firstPrefix, firstCount + 1); prefix = firstPrefix; } else { prefixes.put(secondPrefix, secondCount + 1); prefix = secondPrefix; } answer += (i + 1) - min(firstCount, secondCount); } return answer; } long getBruteAnswer(int n, int k, int[] a, long check) { int high = (1 << k) - 1; long answer = -1; for (int mask = 0; mask < (1 << n); ++mask) { for (int bit = 0; bit < n; ++bit) { if (checkBit(mask, bit)) { a[bit] = high - a[bit]; } } Map<Integer, Integer> prefixes = new HashMap<>(); int prefix = 0; prefixes.put(prefix, 1); long result = 0; for (int i = 0; i < n; ++i) { int value = a[i]; prefix ^= value; int count = prefixes.getOrDefault(prefix, 0); prefixes.put(prefix, count + 1); result += (i + 1) - count; } for (int bit = 0; bit < n; ++bit) { if (checkBit(mask, bit)) { a[bit] = high - a[bit]; } } if (answer < result) { answer = result; } if (answer == result && result == check) { out.println(mask); } } return answer; } ///////////////////////////////////////////////////////////////////// private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long inverse(long x) { return binpow(x, MODULO - 2); } private static long binpow(long base, long power) { if (power == 0) return 1; if ((power & 1) == 0) { long half = binpow(base, power >> 1); return mult(half, half); } else { long prev = binpow(base, power - 1); return mult(prev, base); } } private static long add(long a, long b) { return (a + b) % MODULO; } @SuppressWarnings("unused") private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") void yesNo(boolean yes) { out.println(yes ? "YES" : "NO"); } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException | EOFException e) { break; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new D(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @SuppressWarnings("unused") private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readNullableLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readLine() { String line = readNullableLine(); if (null == line) throw new EOFException(); return line; } private String readString() { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; @SuppressWarnings("unused") private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } @SuppressWarnings("unused") private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } @SuppressWarnings("unused") private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } @SuppressWarnings("unused") private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } @SuppressWarnings("unused") private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } @SuppressWarnings("unused") private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private BigInteger readBigInteger() { return new BigInteger(readString()); } @SuppressWarnings("unused") private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } @SuppressWarnings("unused") private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated @SuppressWarnings("unused") private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { @SuppressWarnings("unchecked") List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } @SuppressWarnings("unused") private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; @SuppressWarnings("unused") private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } @SuppressWarnings("unused") private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { @SuppressWarnings("unused") static Comparator<IntIndexPair> increaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static Comparator<IntIndexPair> decreaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } @SuppressWarnings("unused") int getRealIndex() { return index + 1; } } @SuppressWarnings("unused") private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @SuppressWarnings("unused") void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class EOFException extends RuntimeException { EOFException() { super(); } } private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static void swap(int[] array, int i, int j) { if (i != j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static <T> void swap(T[] array, int i, int j) { if (i != j) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; @SuppressWarnings("unused") private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } @SuppressWarnings("unused") private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } @SuppressWarnings("unused") private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } @SuppressWarnings("unused") private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } @SuppressWarnings("unused") long[] getDivisors(long value) { List<Long> divisors = new ArrayList<>(); for (long divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castLong(divisors); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } @SuppressWarnings("unused") private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ @SuppressWarnings("unused") private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } @SuppressWarnings("unused") private static List<Integer> shuffled(List<Integer> list) { Collections.shuffle(list, rnd); return list; } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
4b7266be4fde72d2218f5e5fda5115e4
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; public class CFD { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int k; int[] arr; Map<Integer, Integer> map; void solve() throws IOException { n = nextInt(); k = nextInt(); arr = nextIntArr(n); map = new HashMap<>(); int sum = 0; map.put(sum, 1); for (int v : arr) { sum = sum ^ v; map.put(sum, map.getOrDefault(sum, 0) + 1); } long res = 1L * n * (n + 1) / 2; Set<Integer> vis = new HashSet<>(); for (int v : map.keySet()) { if (vis.contains(v)) { continue; } int c1 = map.get(v); int comp = ((1 << k) - 1) ^ v; int c2 = map.getOrDefault(comp, 0); int s = c1 + c2; int hf = s / 2; res -= 1L * hf * (hf - 1) / 2; hf = s - hf; res -= 1L * hf * (hf - 1) / 2; vis.add(comp); } outln(res); } 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; } } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFD() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFD(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
590fdbaa264c98d1e593b40fb7f0f7e0
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main4 { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.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 s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static int n; public static long func(int arr[], int n,int k) { long ans = 0; int xorval=0; HashMap<Integer,Integer> hm=new HashMap<>(); hm.put(0,1); for (int i = 0; i < n; i++) { int temp1=xorval^arr[i]; int temp2=xorval^(((int)Math.pow(2,k)-1)^arr[i]); if(hm.getOrDefault(temp1,0)>hm.getOrDefault(temp2,0)) xorval=temp2; else xorval=temp1; ans+=-(long)hm.getOrDefault(xorval,0)+i+1; hm.put(xorval,hm.getOrDefault(xorval,0)+1); } return ans; } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); n=sc.i(); int k=sc.i(); int arr[]=sc.arr(n); out.println(func(arr,n,k)); out.flush(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
190ec042b689de38256f1ad1f2e3dfce
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class D { FastScanner in; PrintWriter out; boolean systemIO = true; public class Pair implements Comparable<Pair> { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x > o.x) { return 1; } if (x < o.x) { return -1; } if (y > o.y) { return 1; } if (y < o.y) { return -1; } return 0; } } public Pair sum(Pair a, Pair b) { return new Pair(a.x + b.x, a.y + b.y); } public class Fenvik { int[] sum; public Fenvik(int n) { sum = new int[n]; } public void add(int x, int d) { for (int i = x; i < sum.length; i = (i | (i + 1))) { sum[i] += d; } } public long sum(int r) { long ans = 0; for (int i = r; i >= 0; i = (i & (i + 1)) - 1) { ans += sum[i]; } return ans; } } public long gcd(long x, long y) { if (y == 0) { return x; } if (x == 0) { return y; } return gcd(y, x % y); } public void solve() { int n = in.nextInt(); int k = in.nextInt(); HashMap<Integer, Integer> map = new HashMap<>(); int mod = (1 << k) - 1; int th = 0; map.put(0, 1); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } long ans = 0; for (int i = 0; i < a.length; i++) { int x = 0; if (map.containsKey(th ^ a[i])) { x = map.get(th ^ a[i]); } int y = 0; if (map.containsKey(th ^ mod ^ a[i])) { y = map.get(th ^ mod ^ a[i]); } if (x < y) { ans += x; } else { a[i] ^= mod; ans += y; } th ^= a[i]; if (map.containsKey(th)) { map.put(th, map.get(th) + 1); } else { map.put(th, 1); } } // System.out.println(ans); // for (int i = 0; i < a.length; i++) { // System.out.print(a[i] + " "); // } // System.out.println(); out.println(n * 1L * (n + 1) / 2 - ans); } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new D().run(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
01d78949df5e3539b8a72079069a99d6
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; public class p7{ 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; } } public static void main(String[] args) { FastReader sc = new FastReader(); //PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); long one = (long)Math.pow(2, k) - 1; long[] arr = new long[n+1]; arr[0] = 0; for(int i=1;i<=n;i++){ arr[i] = sc.nextLong(); arr[i] ^= arr[i-1]; } Map<Long, Long> count = new HashMap<>(); for(int i=0;i<=n;i++){ Long key = Math.min(arr[i], (arr[i]^one)); Long val = count.get(key); if(val==null) val = 0L; count.put(key, val+1); } long num = n; long ans = num*(num+1)/2; for(Map.Entry<Long, Long> ent: count.entrySet()){ Long cnt = ent.getValue(); long num1 = cnt/2; long num2 = (cnt+1)/2; ans -= ( (num1*(num1-1))/2 ); ans -= ( (num2*(num2-1))/2 ); } System.out.println(ans); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
3f6a292a4ba2477755ab92d1e71b26a6
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); void run(){ out.println(work()); out.flush(); } long work() { int n=in.nextInt(); int k=in.nextInt(); int[] A=new int[n]; for(int i=0;i<n;i++) A[i]=in.nextInt(); long c=(long)n; long ret=(1+c)*c/2; int mask=(1<<k)-1; int cur=0; HashMap<Integer,Long> map=new HashMap<>(); map.put(0,1L); for(int i=0;i<n;i++){ int a=cur^A[i]; int b=cur^A[i]^mask; if(map.getOrDefault(a,0L)>=map.getOrDefault(b,0L)){ cur=b; ret-=map.getOrDefault(b,0L); map.put(b,map.getOrDefault(b,0L)+1); }else{ cur=a; ret-=map.getOrDefault(a,0L); map.put(a,map.getOrDefault(a,0L)+1); } } return ret; } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
19c6f89970f73df26e8a0488366fc303
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class D_MailRu { static int k; static int CST; public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextInt(); k = sc.nextInt(); CST = (1 << k) - 1; Map<Integer, Integer> partialSumCounts = new HashMap<>(); int currentPartial = 0; for (int i = 1; i <= n; i++) { int next = sc.nextInt(); currentPartial = currentPartial ^ next; partialSumCounts.put(currentPartial, partialSumCounts.getOrDefault(currentPartial, 0) + 1); } long badSegments = 0; // do case 0 if (partialSumCounts.containsKey(0) || partialSumCounts.containsKey(CST)) { badSegments+= formula(partialSumCounts.getOrDefault(0,0) + 1 + partialSumCounts.getOrDefault(CST, 0)); } Set<Integer> existing = new HashSet<>(partialSumCounts.keySet()); existing.remove(0); existing.remove(CST); for (Integer possible : existing) { int q1 = partialSumCounts.getOrDefault(possible, 0); int q2 = partialSumCounts.getOrDefault(flip(possible), 0); if (q1 + q2 != 0) { badSegments += formula(q1 + q2); partialSumCounts.remove(possible); partialSumCounts.remove(flip(possible)); } } long maxSegments = (n * (n+1))/ 2; System.out.println(maxSegments - badSegments); } private static long formula(long S) { long sol = 0; sol += (S * S - S) / 2; if (S % 2 ==0) { sol -= (S * S) / 4; } else { sol -= (S * S - 1) / 4; } return sol; } private static int flip(int x) { return CST - x; } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
f41457979634cf29195f775e254e1240
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class D extends PrintWriter { void run() { int n = nextInt(), k = nextInt(); int[] a = nextArray(n); int mask = (1 << k) - 1; int xor = 0; for (int i = 0; i < n; i++) { xor ^= a[i]; } long ans = 0; Map<Integer, Integer> cnt = new HashMap<>(); cnt.put(0, 1); for (int i = 0; i < n; i++) { Integer s = cnt.get(xor); if (s == null) { s = 0; } Integer x = cnt.get(xor ^ mask); if (x == null) { x = 0; } if (s <= x) { ans += (int) s; cnt.put(xor, s + 1); xor ^= a[i]; } else { ans += (int) x; cnt.put(xor ^ mask, x + 1); xor ^= a[i] ^ mask; } } println(n * (n + 1L) / 2 - ans); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public D(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; D solution = new D(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(D.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
d19bcb21187335a0aee88883ad64bf63
train_002.jsonl
1539880500
At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { class Node implements Comparable<Node>{ int id; int l; int r; public Node(int id,int l,int r){ this.id=id; this.l=l; this.r=r; } public int compareTo(Node c){ int t=Integer.compare(this.l+this.r,c.l+c.r); return t; } } void solve(){ int n=ni(),k=ni(); long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nl(); HashMap<Long,Long> mp=new HashMap<>(); mp.put((long)0,(long)1); long ans=0; long p=(1<<k)-1; long pref=0; for(int i=1;i<=n;i++){ long x1=a[i],x2=a[i]^p; x1^=pref; x2^=pref; long c1=0,c2=0; if(mp.containsKey(x1)) c1=mp.get(x1); if(mp.containsKey(x2)) c2=mp.get(x2); if(c1<c2){ mp.merge(x1,(long)1,Long::sum); ans+=c1; pref=x1; }else { mp.merge(x2,(long)1,Long::sum); ans+=c2; pref=x2; } } ans=C2(n)-ans; pw.println(ans); } long C2(long n){ n*=(n+1); n/=2; return n; } long M= (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } 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(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["3 2\n1 3 0", "6 3\n1 4 4 7 3 4"]
1 second
["5", "19"]
NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.
Java 8
standard input
[ "implementation", "greedy" ]
71ad4b2e9e888933e55425e73a0d68b5
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.
1,900
Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.
standard output
PASSED
0de4cbab002b8dccde17f51b8c286dc8
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.util.Set; public class cf1000a { public static int dif(String a,String b) { int re = 0 ; for(int i=0;i<a.length();i++) { if(a.charAt(i) != b.charAt(i)) { re += 1 ; } } return re ; } public static void main(String[] args) { InputReader sc = new InputReader(System.in); Map<String,Integer> amap = new HashMap(); String k ; int temp ; int s = Integer.valueOf(sc.nextLine()) ; for(int i=0;i<s;i++) { k = sc.nextLine() ; if(!amap.containsKey(k)) { amap.put(k, 1) ; } else { temp = amap.get(k); amap.put(k, temp+1) ; } } Set keys = amap.keySet() ; ArrayList<String> pre = new ArrayList(); ArrayList<String> ne = new ArrayList(); for(int i=0;i<s;i++) { k = sc.nextLine() ; if(amap.containsKey(k)) { temp = amap.get(k) ; amap.put(k, temp-1) ; } else { ne.add(k) ; } } for(Object t : keys) { temp = (amap.get(t)) ; if(temp >= 0) { for(int i=0;i<temp;i++) { pre.add(String.valueOf(t)) ; } } else{ for(int i=0;i<Math.abs(temp);i++) { ne.add(String.valueOf(t)); } } } temp = pre.size() ; boolean[] mark = new boolean[temp] ; Collections.sort(ne, new Comparator<String>() { public int compare(String o1,String o2) { return o1.length() - o2.length() ; } }); Collections.sort(pre, new Comparator<String>() { public int compare(String o1,String o2) { return o1.length() - o2.length() ; } }); int ans = 0 ; int strsize,min,ind ; for(int i=0,len = ne.size();i<len;i++) { if(ne.get(i).length() == 1) { mark[i] = true ; ans += 1 ; } else { min = Integer.MAX_VALUE ; ind = -1 ; strsize = ne.get(i).length() ; for(int j=0;j<pre.size();j++) { if(pre.get(j).length() == strsize) { temp = j ; break ; } } for(int j=temp; j<len && pre.get(j).length()==strsize;j++) { if(mark[j]) { continue ; } if(min > dif(ne.get(i),pre.get(j))) { min = dif(ne.get(i),pre.get(j)) ; ind = j ; } } ans += min ; mark[ind] = true ; } } System.out.println(ans); } 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); } } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
a10e6ee471e9c22224e5968b3ada76d6
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
//package codeforcesdv246; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String prev[]=new String[n]; String curr[]=new String[n]; for(int i=0;i<n;i++) { prev[i]=sc.next(); } ArrayList<String> al=new ArrayList<String>(); for(int i=0;i<n;i++) { curr[i]=sc.next(); //al.add(curr[i]); } int count=n; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(prev[i].equals(curr[j])) { count--; curr[j]=""; break; } } } System.out.println(count); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
f44011f062df8330f1741cfddd174713
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = sc.next(); Arrays.sort(a); String[] b = new String[n]; for (int i = 0; i < n; i++) b[i] = sc.next(); Arrays.sort(b); int ans = 0; boolean[] taken = new boolean[n]; for (int i = 0; i < n; i++) { boolean found = false; for (int j = 0; j < n; j++) { if (!taken[j] && b[i].equals(a[j])) { found = true; taken[j] = true; break; } } if (!found) ans++; } out.println(ans); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput() throws InterruptedException {Thread.sleep(3000);} } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
6dbbd280e1b3b73f2da9eaa5feb452d9
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class j8 implements Runnable { public void run(){ InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=in.nextInt(); HashMap<String,Integer> ha=new HashMap<String,Integer>(); HashMap<String,Integer> hb=new HashMap<String,Integer>(); for(int i=0;i<n;i++) { String s=in.next(); if(ha.get(s)==null) ha.put(s, 1); else ha.put(s, ha.get(s)+1); } for(int i=0;i<n;i++) { String s=in.next(); if(hb.get(s)==null) hb.put(s, 1); else hb.put(s, hb.get(s)+1); } int ts=0; for(HashMap.Entry<String,Integer> entry : hb.entrySet()) { String s=entry.getKey(); int b1=entry.getValue(); if(ha.get(s)==null) ts+=b1; else if(ha.get(s)>=b1) ts+=0; else ts+=b1-ha.get(s); } w.println(ts); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 j8(),"j8",1<<26).start(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
0f704b3bbcadf76d5bc5cc6f5f072349
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class A { public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); HashMap<String, Integer> prev = new HashMap<>(); for(int i = 0; i < n; i++) { String inp = Reader.next(); if(prev.containsKey(inp)){ prev.put(inp, prev.get(inp)+1);} else{ prev.put(inp,1); } } int out = 0; HashMap<String, Integer> ext = new HashMap<>(); for(int i = 0; i < n; i++){ String inp = Reader.next(); if(prev.containsKey(inp) && prev.get(inp) > 0){prev.put(inp, prev.get(inp)-1);} else{ if(ext.containsKey(inp)){ ext.put(inp, ext.get(inp)+1);} else{ ext.put(inp,1); } } } for(String inp : ext.keySet()){ int len = inp.length(); int tt = ext.get(inp); for(int i = 0; i < tt; i++){ for(String ele : prev.keySet()){ if(ele.length() == len && prev.get(ele) > 0){ prev.put(ele, prev.get(ele) -1); break; } } out++; } } System.out.println(out); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() { return Long.parseLong(nextToken()); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
c328180437706b7d2a3af9008aac4d2e
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
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.*; public class Soly { static final int INF = Integer.MAX_VALUE; static int mergeSort(int[] a,int [] c, int begin, int end) { int inversion=0; if(begin < end) { inversion=0; int mid = (begin + end) >>1; inversion+= mergeSort(a,c, begin, mid); inversion+=mergeSort(a, c,mid + 1, end); inversion+=merge(a,c, begin, mid, end); } return inversion; } static int merge(int[] a,int[]c, int b, int mid, int e) { int n1 = mid - b + 1; int n2 = e - mid; int[] L = new int[n1+1], R = new int[n2+1]; int[] L1 = new int[n1+1], R1 = new int[n2+1]; //inversion int inversion=0; for(int i = 0; i < n1; i++) { L[i] = a[b + i]; L1[i] = c[b + i]; } for(int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; R1[i] = c[mid + 1 + i]; } L[n1] = R[n2] = INF; for(int k = b, i = 0, j = 0; k <= e; k++) if(L[i] <= R[j]){ a[k] = L[i]; c[k] = L1[i++]; } else { a[k] = R[j]; c[k] = R1[j++]; inversion=inversion+(n1-i); } return inversion; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { int n = in.nextInt(); TreeMap<String,Integer> map = new TreeMap<>(); String[] a= new String[n]; for (int i = 0; i < n; i++) { a[i]=in.next(); } for (int i = 0; i < n; i++) { map.merge(in.next(),1,Integer::sum); } int ans=0; for (int i = 0; i < n; i++) { if (map.containsKey(a[i])){ if (map.get(a[i])==1)map.remove(a[i]); else map.put(a[i],map.get(a[i])-1); } else ++ans; } or.println(ans); } } 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(); } } } class coooo implements Comparable<coooo> { int a,c,index; public coooo(int a, int c, int index) { this.a = a; this.c = c; this.index = index; } @Override public int compareTo(coooo o) { if (c!=o.c)return c-o.c; return index-o.index; } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output