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
766761a97e1417ce78e94cd23d851547
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
/* PROG: d LANG: JAVA */ import java.util.*; import java.io.*; public class d { int bs(int[] a, int lo, int hi, int cu, int t) { while(lo < hi) { int mid = (lo + hi) / 2; if(a[mid] - a[cu] < t) { lo = mid + 1; } else { hi = mid; } } return lo; } private void solve() throws IOException { int n = nextInt() + 1; int[] x = new int[n]; int[] y = new int[n]; for(int i = 1; i < n; ++i) { int a = nextInt(); if(a == 1) { x[i] = x[i - 1] + 1; y[i] = y[i - 1]; } else { x[i] = x[i - 1]; y[i] = y[i - 1] + 1; } } List<int[]> v = new ArrayList<>(); for(int t = 1; t < n; ++t) { int lo = 1, lu = 0, hi = n, cu = 0, s1 = 0, s2 = 0, l = 0, a = 0, b = 0; while(lo < hi) { a = bs(x, lo, hi, cu, t); b = bs(y, cu, a, cu, t); if(b < a) { cu = b; lo = b + 1; s2 += 1; l = 2; } else { cu = a; lo = a + 1; s1 += 1; l = 1; } } if(!(a == n && b == n)) { if(s1 > s2 && l == 1) v.add(new int[] {s1, t}); if(s2 > s1 && l == 2) v.add(new int[] {s2, t}); } } Collections.sort(v, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] == b[0]) return a[1] - b[1]; return a[0] - b[0]; } }); System.out.println(v.size()); for(int[] i : v) System.out.println(i[0] + " " + i[1]); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } BufferedReader br; StringTokenizer st; PrintWriter out = new PrintWriter(System.out); 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()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } private void run() throws IOException { //br = new BufferedReader(new FileReader("d.in")); br = new BufferedReader(new InputStreamReader(System.in)); solve(); out.close(); } public static void main(String[] args) throws IOException { new d().run(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
67ae69b3f783a54d487ca3128a101f9f
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
/* PROG: d LANG: JAVA */ import java.util.*; import java.io.*; public class d { int bs(int[] a, int lo, int hi, int cu, int t) { while(lo < hi) { int mid = (lo + hi) / 2; if(a[mid] - a[cu] < t) { lo = mid + 1; } else { hi = mid; } } return lo; } private void solve() throws IOException { int n = nextInt() + 1; int[] x = new int[n]; int[] y = new int[n]; for(int i = 1; i < n; ++i) { int a = nextInt(); if(a == 1) { x[i] = x[i - 1] + 1; y[i] = y[i - 1]; } else { x[i] = x[i - 1]; y[i] = y[i - 1] + 1; } } List<int[]> v = new ArrayList<>(); for(int t = 1; t < n; ++t) { int lo = 1, lu = 0, hi = n, cu = 0, s1 = 0, s2 = 0, l = 0, a = 0, b = 0; while(lo < hi) { a = bs(x, lo, hi, cu, t); b = bs(y, cu, a, cu, t); if(b < a) { cu = b; lo = b + 1; s2 += 1; l = 2; } else { cu = a; lo = a + 1; s1 += 1; l = 1; } } if(!(a == n && b == n)) { if(s1 > s2 && l == 1) v.add(new int[] {s1, t}); if(s2 > s1 && l == 2) v.add(new int[] {s2, t}); } } Collections.sort(v, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] == b[0]) return a[1] - b[1]; return a[0] - b[0]; } }); out.println(v.size()); for(int[] i : v) out.println(i[0] + " " + i[1]); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } BufferedReader br; StringTokenizer st; PrintWriter out = new PrintWriter(System.out); 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()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } private void run() throws IOException { //br = new BufferedReader(new FileReader("d.in")); br = new BufferedReader(new InputStreamReader(System.in)); solve(); out.close(); } public static void main(String[] args) throws IOException { new d().run(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
035a007a01cddbe9686169928771ba42
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
/* PROG: b LANG: JAVA */ import java.util.*; import java.io.*; public class b { int bt(int[] x, int lo, int hi, int cu, int v) { while(lo < hi) { int mid = (lo + hi) / 2; if(x[mid] - x[cu] < v) { lo = mid + 1; } else { hi = mid; } } return lo; } int bs(int[] x, int[] y, int v) { int lo = 1, n = x.length, hi = n, cu = 0, r = 0, d = 0, s = 0; while(lo < n) { while(lo < hi) { int mid = (lo + hi) / 2; if(x[mid] - x[cu] < v) { lo = mid + 1; } else { hi = mid; } } if(lo == n) return -1; int ys = bt(y, cu, lo, cu, v); if(ys < lo) { ++s; cu = ys; } else if(lo < n) { ++r; cu = lo; lo = lo + 1; } hi = n; } return r <= s ? -1 : r; } private void solve() throws Exception { //BufferedReader br = new BufferedReader(new FileReader("b.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] pa = br.readLine().split(" "); int[] a = new int[n]; int[] x = new int[n + 1]; int[] y = new int[n + 1]; for(int i = 0; i < n; ++i) { a[i] = Integer.parseInt(pa[i]); if(a[i] == 1) { x[i + 1] = x[i] + 1; y[i + 1] = y[i]; } else { x[i + 1] = x[i]; y[i + 1] = y[i] + 1; } } //bf(a); //debug(2, bs(y, x, 2)); List<int[]> r = new ArrayList<>(); for(int p = 1; p <= n; ++p) { int xb = bs(x, y, p); int yb = bs(y, x, p); if(xb == yb) continue; //debug(xb, yb); if(xb > yb && xb > 0) { r.add(new int[] {xb, p}); //debug('x',p, xb); } if(yb > xb && yb > 0) { r.add(new int[] {yb, p}); //debug('y',p, yb); } } Collections.sort(r, new Comparator<int[]>() { public int compare(int[] aa, int[] bb) { if(aa[0] == bb[0]) { return aa[1] - bb[1]; } return aa[0] - bb[0]; } }); System.out.println(r.size()); for(int[] i : r) System.out.println(i[0] + " " + i[1]); } public static void main(String[] args) throws Exception { new b().solve(); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
ebdad6837c880bf6f08f118d11b7e3e7
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.*; import java.io.*; public class b { int bt(int[] x, int lo, int hi, int cu, int v) { while(lo < hi) { int mid = (lo + hi) / 2; if(x[mid] - x[cu] < v) { lo = mid + 1; } else { hi = mid; } } return lo; } int[] bs(int[] x, int[] y, int v) { int lo = 1, n = x.length, hi = n, cu = 0, s1 = 0, s2 = 0, ys = 0, d = 0; while(lo < n) { lo = bt(x, lo, hi, cu, v); ys = bt(y, cu, lo, cu, v); if(lo == n && ys == n) return null; if(ys < lo) { ++s2; cu = ys; lo = ys + 1; d = 2; } else if(lo < n) { ++s1; cu = lo; lo = lo + 1; d = 1; } } if(s1 > s2 && d == 1) return new int[]{s1, v}; if(s2 > s1 && d == 2) return new int[]{s2, v}; return null; } private void solve() throws Exception { //BufferedReader br = new BufferedReader(new FileReader("b.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] pa = br.readLine().split(" "); int[] a = new int[n]; int[] x = new int[n + 1]; int[] y = new int[n + 1]; for(int i = 0; i < n; ++i) { a[i] = Integer.parseInt(pa[i]); if(a[i] == 1) { x[i + 1] = x[i] + 1; y[i + 1] = y[i]; } else { x[i + 1] = x[i]; y[i + 1] = y[i] + 1; } } List<int[]> r = new ArrayList<>(); //debug(4, bs(y, x, 4)); for(int p = 1; p <= n; ++p) { int[] xb = bs(y, x, p); if(xb != null) r.add(xb); } Collections.sort(r, new Comparator<int[]>() { public int compare(int[] aa, int[] bb) { if(aa[0] == bb[0]) { return aa[1] - bb[1]; } return aa[0] - bb[0]; } }); System.out.println(r.size()); for(int[] i : r) System.out.println(i[0] + " " + i[1]); } public static void main(String[] args) throws Exception { new b().solve(); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
810eaa18a6587b9a4ee6944e0d5fe50b
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
/* PROG: d LANG: JAVA */ import java.util.*; import java.io.*; public class d { int bs(int[] a, int lo, int hi, int cu, int t) { while(lo < hi) { int mid = (lo + hi) / 2; if(a[mid] - a[cu] < t) { lo = mid + 1; } else { hi = mid; } } return lo; } private void solve() throws IOException { int n = nextInt() + 1; int[] x = new int[n]; int[] y = new int[n]; for(int i = 1; i < n; ++i) { int a = nextInt(); if(a == 1) { x[i] = x[i - 1] + 1; y[i] = y[i - 1]; } else { x[i] = x[i - 1]; y[i] = y[i - 1] + 1; } } List<int[]> v = new ArrayList<>(); a: for(int t = 1; t < n; ++t) { int lo = 1, lu = 0, hi = n, cu = 0, s1 = 0, s2 = 0, l = 0, a = 0, b = 0; while(lo < hi) { a = bs(x, lo, hi, cu, t); b = bs(y, cu, a, cu, t); //debug(a, b, n, lo); if(b < a) { cu = b; lo = b + 1; s2 += 1; l = 2; } else { cu = a; lo = a + 1; s1 += 1; l = 1; } } if(a == n && b == n) continue a; if(s1 > s2 && l == 1) v.add(new int[] {s1, t}); if(s2 > s1 && l == 2) v.add(new int[] {s2, t}); } Collections.sort(v, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] == b[0]) return a[1] - b[1]; return a[0] - b[0]; } }); System.out.println(v.size()); for(int[] i : v) System.out.println(i[0] + " " + i[1]); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } BufferedReader br; StringTokenizer st; PrintWriter out = new PrintWriter(System.out); 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()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } private void run() throws IOException { //br = new BufferedReader(new FileReader("d.in")); br = new BufferedReader(new InputStreamReader(System.in)); solve(); out.close(); } public static void main(String[] args) throws IOException { new d().run(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
f319b7297a98202342efab86e15c3dd5
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.*; import java.io.*; public class b { int bt(int[] x, int lo, int hi, int cu, int v) { while(lo < hi) { int mid = (lo + hi) / 2; if(x[mid] - x[cu] < v) { lo = mid + 1; } else { hi = mid; } } return lo; } int[] bs(int[] x, int[] y, int v) { int lo = 1, n = x.length, hi = n, cu = 0, s1 = 0, s2 = 0, ys = 0, d = 0; while(lo < n) { lo = bt(x, lo, hi, cu, v); ys = bt(y, cu, lo, cu, v); if(lo == n && ys == n) return null; if(ys < lo) { ++s2; cu = ys; lo = ys + 1; d = 2; } else if(lo < n) { ++s1; cu = lo; lo = lo + 1; d = 1; } } if(lo == n) { if(s1 > s2 && d == 1) return new int[]{s1, v}; if(s2 > s1 && d == 2) return new int[]{s2, v}; } return null; } private void solve() throws Exception { //BufferedReader br = new BufferedReader(new FileReader("b.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] pa = br.readLine().split(" "); int[] a = new int[n]; int[] x = new int[n + 1]; int[] y = new int[n + 1]; for(int i = 0; i < n; ++i) { a[i] = Integer.parseInt(pa[i]); if(a[i] == 1) { x[i + 1] = x[i] + 1; y[i + 1] = y[i]; } else { x[i + 1] = x[i]; y[i + 1] = y[i] + 1; } } List<int[]> r = new ArrayList<>(); //debug(4, bs(y, x, 4)); for(int p = 1; p <= n; ++p) { int[] xb = bs(y, x, p); if(xb != null) r.add(xb); } Collections.sort(r, new Comparator<int[]>() { public int compare(int[] aa, int[] bb) { if(aa[0] == bb[0]) { return aa[1] - bb[1]; } return aa[0] - bb[0]; } }); System.out.println(r.size()); for(int[] i : r) System.out.println(i[0] + " " + i[1]); } public static void main(String[] args) throws Exception { new b().solve(); } static void debug(Object...o) { System.err.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
d644be960c3c00b4b37b4b4d44368282
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public final class CF_TennisGame { void log(int[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } void log(long[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } void log(Object[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } void log(Object o){ logWln(o+"\n"); } void logWln(Object o){ //System.out.print(o); outputWln(o); } void info(Object o){ System.out.println(o); //output(o); } void output(Object o){ outputWln(""+o+"\n"); } void outputWln(Object o){ // System.out.print(o); try { out.write(""+ o); } catch (Exception e) { } } String next(){ while (st== null|| !st.hasMoreTokens()) { try { st=new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } String nextLine(){ try { return in.readLine(); } catch (Exception e) { } return null; } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } // Global vars StringTokenizer st; BufferedReader in; BufferedWriter out; class Composite implements Comparable<Composite> { int s; int t; public int compareTo(Composite X){ if (s<X.s) return s-X.s; return t-X.t; } public Composite(int s,int t){ this.s=s; this.t=t; } public String toString(){ return s+" "+t; } } void solve(int[] a,int N,int sum1,int sum2,int[] ssum1,int[] ssum2){ int tmax=Math.max(sum1,sum2); ArrayList<Composite> res=new ArrayList<Composite>(); for (int t=1;t<=tmax;t++){ int i=0; int s1=0; int s2=0; int last=0; loop: while(i<N){ int old1=0,old2=0; if (i>0){ old1=ssum1[i-1]; old2=ssum2[i-1]; } int idx1=Arrays.binarySearch(ssum1,t+old1); int idx2=Arrays.binarySearch(ssum2,t+old2); //log("t:"+t+" idx1:"+idx1+" idx2:"+idx2); if (idx1<0 && idx2<0) break loop; if (idx1>=0 && idx2>=0){ int u=idx1; while (u-1>=0 && ssum1[u-1]==ssum1[u]) u--; int v=idx2; while (v-1>=0 && ssum2[v-1]==ssum2[v]) v--; if (u<v) { s1++; i=u+1; last=1; //log("case 1"); } else { s2++; i=v+1; last=2; //log("case 2"); } } else { if (idx1<0){ int v=idx2; while (v-1>=0 && ssum2[v-1]==ssum2[v]) v--; s2++; i=v+1; last=2; //log("case 3"); } else { int u=idx1; while (u-1>=0 && ssum1[u-1]==ssum1[u]) u--; s1++; i=u+1; last=1; //log("case 4"); } } if (i==N){ if (s1>s2 && last==1) res.add(new Composite(s1,t)); if (s2>s1 && last==2) res.add(new Composite(s2,t)); } } } Collections.sort(res); output(res.size()); for (Composite X:res) output(X); } void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); in=new BufferedReader(new InputStreamReader(System.in)); int N=nextInt(); int[] a=new int[N]; int sum1=0; int sum2=0; int[] ssum1=new int[N]; int[] ssum2=new int[N]; for (int i=0;i<N;i++) { a[i]=nextInt(); if (i>0){ ssum1[i]=ssum1[i-1]; ssum2[i]=ssum2[i-1]; } if (a[i]==1){ sum1++; ssum1[i]++; } else { sum2++; ssum2[i]++; } } solve(a,N,sum1,sum2,ssum1,ssum2); try { out.close(); } catch (Exception e){} } public static void main(String[] args) throws Exception { CF_TennisGame J=new CF_TennisGame(); J.process(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
f47c907aa220214bf41258178688105e
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.*; public class b { public static void main(String[] args) { Scanner input = new Scanner(System.in); n = input.nextInt(); int[] data = new int[n]; for(int i = 0; i<n; i++) data[i] = input.nextInt(); TreeSet<Pair> res = new TreeSet<Pair>(); precomp(data); for(int i = 1; i<=n; i++) { int s = getS(i, data); if(s == -1) continue; res.add(new Pair(s, i)); } System.out.println(res.size()); for(Pair p: res) System.out.println(p.s+" "+p.t); } static class Pair implements Comparable<Pair> { int s, t; public Pair(int ss, int tt) { s = ss; t = tt; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if(s != o.s) return s - o.s; return t - o.t; } } static int n; static int[] getA, getB, scoreA, scoreB; static void precomp(int[] data) { scoreA = new int[n]; scoreB = new int[n]; for(int i = 0; i<n; i++) { int lastA = (i == 0 ? 0 : scoreA[i-1]); int lastB = (i == 0 ? 0 : scoreB[i-1]); scoreA[i] = data[i] == 1 ? lastA + 1 : lastA; scoreB[i] = data[i] == 2 ? lastB + 1 : lastB; } getA = new int[n]; getB = new int[n]; int atA = 0, atB = 0; Arrays.fill(getA, n); Arrays.fill(getB, n); for(int i = 0; i<n; i++) { if(data[i] == 1) getA[atA++] = i; else getB[atB++] = i; } } static int getS(int t, int[] data) { int sa = 0, sb = 0; boolean end = false; int usedA = -1, usedB = -1; //int at = 0; while(true) { int nextA = usedA + t >= n ? n : getA[usedA + t]; int nextB = usedB + t >= n ? n : getB[usedB + t]; int nextPos = Math.min(nextA, nextB); if(nextPos >= n) break; if(data[nextPos] == 1) { sa++; } else sb++; usedA = scoreA[nextPos]-1; usedB = scoreB[nextPos]-1; if(nextPos == n-1) end = true; //System.out.println(nextPos); //at = nextPos; } //System.out.println(t+" "+sa+" "+sb+" "+end); if(!end) return -1; if(data[n-1] == 1 && sa > sb) return sa; if(data[n-1] == 2 && sb> sa) return sb; return -1; } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
c96b766b952879afece22364fd044eb9
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.*; import java.util.*; public class problem496D { public static void main(String[]args)throws IOException{ BufferedReader x=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(x.readLine()); int[]arr=new int[n]; HashMap<Integer,Integer>pre1=new HashMap<Integer,Integer>(); HashMap<Integer,Integer>pre2=new HashMap<Integer,Integer>(); StringTokenizer st=new StringTokenizer(x.readLine()); int one=0; int two=0; int[]sum1=new int[n]; int[]sum2=new int[n]; for (int i=0; i<n; i++){ arr[i]=Integer.parseInt(st.nextToken()); if (arr[i]==1){ one++; pre1.put(one,i);//points won, index if (i==0)sum1[0]=1; else{sum1[i]=sum1[i-1]+1;sum2[i]=sum2[i-1];} } if (arr[i]==2){ two++; pre2.put(two,i); if (i==0)sum2[0]=1; else{sum2[i]=sum2[i-1]+1;sum1[i]=sum1[i-1];} } } int count=0; ArrayList<Point>ans=new ArrayList<Point>(); for (int i=1; i<=n; i++){//t, or # of points needed to win set int cur=0;//current index int points1=0; int points2=0; int score1=0; int score2=0; boolean last=false; while (true){ Integer temp1=pre1.get(points1+i); Integer temp2=pre2.get(points2+i); if (temp1==null && temp2==null)break; if (temp1==null)temp1=100000000; if (temp2==null)temp2=100000000; if (temp1<temp2){ score1++; last=false; }else{ score2++; last=true; } int min=Math.min(temp1,temp2); points1=sum1[min]; points2=sum2[min]; cur=min; } if (cur==n-1 && score1!=score2 && ((score1>score2) ^ last)){ count++; ans.add(new Point(Math.max(score1,score2),i)); } } Collections.sort(ans); System.out.println(count); for (Point cur:ans){ System.out.println(cur.x+" "+cur.y); } } } class Point implements Comparable<Point>{ int x; int y; Point(int a, int b){ x=a;y=b; } public int compareTo(Point p){ if (p.x==this.x){ return this.y-p.y; }else{ return this.x-p.x; } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
1b2abd5ee000b2a7883738b509fcd151
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; public class D_TennisGame { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); // StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int[n+1]; a[0] = 0; for (int i = 1; i <= n; i++) { a[i] = Integer.parseInt(st.nextToken()); } TreeSet<Pair> set = solve(n, a); System.out.print( print(set) ); } private static String print(TreeSet<Pair> set) { StringBuilder sb = new StringBuilder(); sb.append(set.size()).append('\n'); for (Pair p : set) { sb.append(p.s).append(' ').append(p.t).append('\n'); } return sb.toString(); } static int s1, s2; static int[] idx1; // index for count static int[] idx2; // index for count static int[] cnt1; // index for count static int[] cnt2; // index for count private static TreeSet<Pair> solve(int n, int[] a) { // initialize s1 = 0; s2 = 0; idx1 = new int[2*n+10]; Arrays.fill(idx1, 0); idx2 = new int[2*n+10]; cnt1 = new int[n+1]; cnt2 = new int[n+1]; cnt1[0] = 0; cnt2[0] = 0; Arrays.fill(idx2, 0); for (int i = 1; i <= n; i++) { cnt1[i] = cnt1[i-1]; cnt2[i] = cnt2[i-1]; if (a[i] == 1) { ++s1; idx1[s1] = i; ++cnt1[i]; } else { ++s2; idx2[s2] = i; ++cnt2[i]; } } TreeSet<Pair> set = new TreeSet<>(); int s; for (int t = 1; t <= n; t++) { s = reply(t); if ( s > 0 ) { set.add(new Pair(s, t)); } } return set; } private static int reply(int t) { int cs1 = 0; int cs2 = 0; int w1 = 0; int w2 = 0; int lidx1 = idx1[cs1 + t]; int lidx2 = idx2[cs2 + t]; int lidx = minIdx( lidx1, lidx2 ); int l = 0; while (lidx > 0 ) { cs1 = cnt1[lidx]; cs2 = cnt2[lidx]; if (lidx == lidx1 ) { ++w1; l = 1; } if (lidx == lidx2 ) { ++w2; l = 2; } lidx1 = idx1[cs1 + t]; lidx2 = idx2[cs2 + t]; lidx = minIdx( lidx1, lidx2 ); } if ( s1 == cs1 && s2 == cs2 ) { if (w1 == w2 ) { return 0; } else { if (w1 > w2 && l == 1) { return w1; } else if ( w2 > w1 && l ==2 ) { return w2; } else { return -2; } } } else { return -1; } } private static int minIdx(int idx1, int idx2) { if ( idx1 == 0 ) return idx2; if ( idx2 == 0 ) return idx1; return Math.min( idx1, idx2 ); } static class Pair implements Comparable<Pair> { int s, t; public Pair(int s, int t) { this.s = s; this.t = t; } @Override public int compareTo(Pair p) { if ( s == p.s ) { return Integer.compare(t, p.t); } else { return Integer.compare(s, p.s); } } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
6beededfda9f3d2de84a1bf8f8994361
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
// package Div2; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Sketch { private static final int LEN = 10000000; private static int findNext(int start, int tval, int[] first, int[] second){ int n = first.length-1; int hd = start; int tl = n; int firstWin = n+1; int secWin = n+1; while(hd != tl){ int mid = (hd+tl)/2; if(first[mid] - first[start-1] >= tval){ tl = mid; } else { hd = mid+1; } } if(first[hd] - first[start-1] == tval) firstWin = hd; hd = start; tl = n; while(hd != tl){ int mid = (hd+tl)/2; if(second[mid] - second[start-1] >= tval){ tl = mid; } else { hd = mid+1; } } if(second[hd] - second[start-1] == tval) secWin = hd; return firstWin<secWin? firstWin : secWin; } private static void sortArray(int[] S, int[] T, int head, int tail){ if(head > tail) return; int mid = (head+tail)/2; int tmp = S[mid]; S[mid] = S[head]; S[head] = tmp; tmp = T[mid]; T[mid] = T[head]; T[head] = tmp; int hd = head; int tl = tail; while(hd != tl){ for(; tl>hd; tl--){ if(S[hd] > S[tl] || (S[hd] == S[tl] && T[hd] > T[tl])){ tmp = S[hd]; S[hd] = S[tl]; S[tl] = tmp; tmp = T[hd]; T[hd] = T[tl]; T[tl] = tmp; break; } } for(; hd<tl; hd++){ if(S[hd] > S[tl] || (S[hd] == S[tl] && T[hd] > T[tl])){ tmp = S[hd]; S[hd] = S[tl]; S[tl] = tmp; tmp = T[hd]; T[hd] = T[tl]; T[tl] = tmp; break; } } } sortArray(S, T, head, hd-1); sortArray(S, T, hd+1, tail); } public static void main(String[] args){ Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] first = new int[n+1]; int[] second = new int[n+1]; for(int i=1; i<=n; i++){ int tag = input.nextInt(); if(tag == 1){ first[i] = first[i-1] +1; second[i] = second[i-1]; } else { first[i] = first[i-1]; second[i] = second[i-1] +1; } } input.close(); int[] sset = new int[LEN]; int[] tset = new int[LEN]; int endOfSet = 0; for(int tval = 1; tval <= n; tval++){ int fwins = 0; int swins = 0; int cur = 1; boolean flag = true; int lastWin = -1; while(cur <= n){ int next = findNext(cur, tval, first, second); if(next == n+1){ flag = false; break; } if(first[next] - first[cur-1] == tval){ fwins++; lastWin = 1; } else { swins++; lastWin = 2; } cur = next+1; } if(!flag) continue; if(fwins > swins && lastWin == 1 || fwins < swins && lastWin == 2){ sset[endOfSet] = fwins>swins? fwins : swins; tset[endOfSet++] = tval; } } sortArray(sset, tset, 0, endOfSet-1); System.out.println(endOfSet); for(int i=0; i<endOfSet; i++){ System.out.println(sset[i] + " " + tset[i]); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
2a5c67199e7c111493a23c10682b383b
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class D_Round_283_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[] data = new int[n]; int[] p = new int[n]; int[] s = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); if (data[i] == 1) { p[i]++; } else { s[i]++; } if (i > 0) { p[i] += p[i - 1]; s[i] += s[i - 1]; } } ArrayList<Point> result = new ArrayList(); if (p[n - 1] != s[n - 1]) { if (p[n - 1] > s[n - 1] && data[n - 1] == 1) { result.add(new Point(Math.max(p[n - 1], s[n - 1]), 1)); } else if (s[n - 1] > p[n - 1] && data[n - 1] == 2) { result.add(new Point(Math.max(p[n - 1], s[n - 1]), 1)); } } for (int i = 2; i <= n - Math.min(p[n - 1], s[n - 1]); i++) { int index = 0; int a = 0; int b = 0; boolean ok = true; while (index < n) { int start = index; int end = n - 1; int x = -1; int last = (index > 0 ? p[index - 1] : 0); while (start <= end) { int mid = (start + end) >> 1; if (p[mid] - last < i) { start = mid + 1; } else if (p[mid] - last >= i) { if (p[mid] - last == i) { if (x == -1 || x > mid) { x = mid; } } end = mid - 1; } } int y = -1; last = (index > 0 ? s[index - 1] : 0); start = index; end = n - 1; while (start <= end) { int mid = (start + end) >> 1; if (s[mid] - last < i) { start = mid + 1; } else if (s[mid] - last >= i) { if (s[mid] - last == i) { if (y == -1 || y > mid) { y = mid; } } end = mid - 1; } } if (x == -1 && y == -1) { ok = false; break; } else if (x != -1 && y != -1) { if (x < y) { a++; index = x + 1; } else { b++; index = y + 1; } } else if (x != -1) { a++; index = x + 1; } else { b++; index = y + 1; } } if (ok) { if (a != b) { if (a > b && data[n - 1] == 1){ result.add(new Point(Math.max(a, b), i)); }else if(a < b && data[n - 1] == 2){ result.add(new Point(Math.max(a, b), i)); } } } } Collections.sort(result, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if (o1.x != o2.x) { return o1.x - o2.x; } return o1.y - o2.y; } }); out.println(result.size()); for (Point point : result) { out.println(point.x + " " + point.y); } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
5076be317bb78009fbdc6c27ccebbdc3
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; public class B { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; B() throws IOException { // reader = new BufferedReader(new FileReader("cycle2.in")); // writer = new PrintWriter(new FileWriter("cycle2.out")); } String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } int[][] mul(int[][] a, int[][] b) { int[][] result = new int[2][2]; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { result[i][j] = sum(result[i][j], product(a[i][k], b[k][j])); } } } return result; } int[][] pow(int[][] a, int k) { int[][] result = {{1, 0}, {0, 1}}; while(k > 0) { if(k % 2 == 1) { result = mul(result, a); } a = mul(a, a); k /= 2; } return result; } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int)(1l * a * b % MOD); } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = nextInt(); } int[][] p = new int[2][n + 1]; for(int i = 1; i <= n; i++) { for(int j = 0; j < 2; j++) { p[j][i] = p[j][i - 1] + (a[i - 1] == j + 1 ? 1 : 0); } } int[][] f = new int[2][]; for(int i = 0; i < 2; i++) { f[i] = new int[2 * n]; Arrays.fill(f[i], Integer.MAX_VALUE); int index = 0; for(int j = 0; j < n; j++) { if(a[j] == i + 1) { f[i][index++] = j; } } } class Pair { int s, t; Pair(int s, int t) { this.s = s; this.t = t; } } List<Pair> answer = new ArrayList<>(); for(int t = 1; t <= n; t++) { int[] ix = new int[2]; int[] lw = new int[2]; int[] s = new int[2]; int last = -1; boolean good = true; while(true) { boolean finish = true; for(int i = 0; i < 2; i++) { if(f[i][ix[i]] != Integer.MAX_VALUE) { finish = false; } lw[i] = ix[i] + t - 1; } if(finish) { break; } boolean bad = true; for(int i = 0; i < 2; i++) { if(f[i][lw[i]] != Integer.MAX_VALUE) { bad = false; } } if(bad) { good = false; break; } for(int i = 0; i < 2; i++) { if(f[i][lw[i]] < f[i + 1 & 1][lw[i + 1 & 1]]) { s[i]++; ix[i] = lw[i] + 1; ix[i + 1 & 1] = p[i + 1 & 1][f[i][lw[i]]]; last = i; break; } } } if(s[0] == s[1]) { good = false; } if(good && s[last] < s[last + 1 & 1]) { good = false; } if(good) { answer.add(new Pair(Math.max(s[0], s[1]), t)); } } Collections.sort(answer, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.s == o2.s) { return o1.t - o2.t; } return o1.s - o2.s; } }); writer.println(answer.size()); for (Pair pair : answer) { writer.println(pair.s + " " + pair.t); } writer.close(); } public static void main(String[] args) throws IOException { new B().solve(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
d3de10a9053b2331e5e416a0177366e8
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { static final long MODULO = (long) (1e9 + 7); private List<Output> result = new ArrayList<Output>(); private int[] ss1; private int[] ss2; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a = 0; int b = 0; int m[] = new int[n]; ss1 = new int[n+1]; ss2 = new int[n+1]; for (int i = 0; i < n; ++i) { m[i] = in.nextInt(); if (m[i] == 1) { a++; } else { b++; } ss1[i+1] = a; ss2[i+1] = b; } int max = Math.max(a, b); for (int t = max; t >= 1; --t) { int s = check(m, t); if (s != 0) { Output o = new Output(); o.s = s; o.t = t; result.add(o); } } Collections.sort(result); out.println(result.size()); for (int i = 0; i < result.size(); i++) { out.print(result.get(i).s + " "); out.print(result.get(i).t); out.println(); } } public static class Output implements Comparable<Output> { int s; int t; @Override public int compareTo(Output o) { if (s > o.s) { return 1; } else if (s == o.s) { if (t <= o.t) { return -1; } else { return 1; } } else { return -1; } } } private int check(int[] m, int t) { int index = 0; int s1 = 0; int s2 = 0; int last = 0; while (index < m.length) { int maxEnd = Math.min(index + 2 * t - 1, m.length); if (ss1[maxEnd] - ss1[index] < t && ss2[maxEnd] - ss2[index] < t) { return 0; } int endIndex1 = find(m, index, maxEnd, t, ss1); int endIndex2 = find(m, index, maxEnd, t, ss2); if (endIndex1 == -1 && endIndex2 == -1) { return 0; } else if (endIndex1 == -1) { s2++; last = 2; index = endIndex2; } else if (endIndex2 == -1) { s1++; last = 1; index = endIndex1; } else { if (endIndex1 < endIndex2) { s1++; last = 1; index = endIndex1; } else { s2++; last = 2; index = endIndex2; } } } // System.out.println(t + ":" + s1 + " " + s2+" ("+t1+"="+t2+")"); if (s1 == s2) { return 0; } else if (s1 > s2 && last == 1) { return s1; } else if (s2 > s1 && last == 2) { return s2; } return 0; } private int find(int[] m, int index, int maxIndex, int t, int[] ss) { int min = index; while (index <= maxIndex) { int mid = (index + maxIndex) / 2; if (ss[mid] - ss[min] == t) { while (mid >= 0 && ss[mid] - ss[min] == t) { mid--; } return mid + 1; } else if (ss[mid] - ss[min] > t) { maxIndex = mid - 1; } else { index = mid + 1; } } return -1; } } class TaskA { static final long MODULO = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } int m = Integer.MAX_VALUE; int max = 0; for (int i = 1; i < n; ++i) { max = Math.max(max, a[i] - a[i - 1]); } for (int i = 1; i < n - 1; ++i) { m = Math.min(m, a[i + 1] - a[i - 1]); if (m <= max) { m = max; break; } } out.println(m); } } class TaskB { static final long MODULO = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String number = in.next(); byte[] maxNum = new byte[n]; Arrays.fill(maxNum, (byte) 9); BigInteger min = new BigInteger(maxNum); for (int inc = 0; inc < 10; ++inc) { for (int shift = 0; shift < n; ++shift) { BigInteger updatedNumber = getNumber(number, inc, shift); if (updatedNumber.compareTo(min) == -1) { min = updatedNumber; } } } if (min.toString().length() < n) { int minm = n - min.toString().length(); for (int i = 0; i < minm; ++i) { System.out.print('0'); } } out.print(min.toString()); out.println(); } private BigInteger getNumber(String number, int inc, int shift) { StringBuffer buffNumber = new StringBuffer(number); for (int i = 0; i < number.length(); ++i) { buffNumber.setCharAt(i, (char) (buffNumber.charAt(i) + inc)); if (buffNumber.charAt(i) > '9') { buffNumber.setCharAt(i, (char) (buffNumber.charAt(i) - 10)); } } int length = buffNumber.length(); // System.out.println(length+" "+shift+" "+buffNumber.substring(length - // shift)+buffNumber.substring(0, length - shift)); return new BigInteger(buffNumber.substring(length - shift) + buffNumber.substring(0, length - shift)); } } class TaskC { static final long MODULO = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); if (n == 1) { out.println("0"); return; } StringBuffer[] str = new StringBuffer[n]; for (int i = 0; i < n; ++i) { str[i] = new StringBuffer(in.next()); } while (true) { boolean retry = false; for (int i = 0; i < n - 1; ++i) { if (!compareStrings(str, i, i + 1)) { retry = true; break; } } if (!retry) { break; } } out.println(m - str[0].length()); } private boolean compareStrings(StringBuffer[] str, int a, int b) { StringBuffer less = str[a]; StringBuffer gt = str[b]; for (int i = 0; i < less.length(); ++i) { if (gt.charAt(i) > less.charAt(i)) { return true; } else if (gt.charAt(i) < less.charAt(i)) { remove(str, i); return false; } } return true; } private void remove(StringBuffer[] str, int removeIndex) { for (int i = 0; i < str.length; ++i) { str[i].deleteCharAt(removeIndex); } } } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
65dbe6204cd256ed9e5375740561d0e4
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.*; import java.util.*; public class CF_496D { public static void main(String[] args) throws IOException { new CF_496D().solve(); } int getT(int[] acc1, int[] acc2, int s){ // System.out.println("start with s: "+s); // System.out.println(Arrays.toString(acc2)); int startSet=0, win1=0, win2=0; int lastwin=0; while (startSet<acc1.length-1){ int bad=startSet, good=acc1.length-1; // if (s==1) { // System.out.println(startSet); // System.out.println(Math.max(acc1[good]-acc1[startSet],acc2[good]-acc2[startSet])); // System.out.println((Math.max(acc1[good]-acc1[startSet],acc2[good]-acc2[startSet])<s)); // } if (Math.max(acc1[good]-acc1[startSet],acc2[good]-acc2[startSet])<s) return -1; while (good-bad>1){ int m=(good+bad)/2; if (Math.max(acc1[m]-acc1[startSet], acc2[m]-acc2[startSet])>=s) good=m; else bad=m; } // System.out.println(good); if (acc1[good]-acc1[startSet]==s) { win1++; lastwin=1; } else { win2++; lastwin=2; } startSet=good; } // System.out.println(win1+" "+win2); if (win1==win2) return -1; if (win1>win2 && lastwin==2) return -1; if (win2>win1 && lastwin==1) return -1; return Math.max(win1, win2); } void solve() throws IOException{ InputStream in = System.in; PrintStream out = System.out; // in = new FileInputStream("in.txt"); // out = new PrintStream("out.txt"); Scanner sc=new Scanner(in); int n=sc.nextInt(); int[] acc1=new int[n+1], acc2=new int[n+1]; for (int i=1;i<acc1.length;i++){ acc1[i]=acc1[i-1]; acc2[i]=acc2[i-1]; if (sc.nextInt()==1) acc1[i]++; else acc2[i]++; } int goodS=0; PriorityQueue<int[]> q=new PriorityQueue<int[]>(100, new Comparator<int[]>(){ @Override public int compare(int[] a, int[]b){ if (a[0]<b[0]) return -1; if (a[0]>b[0]) return 1; if (a[1]<b[1]) return -1; if (a[1]>b[1]) return 1; return 0; } }); for (int s=1;s<=n;s++){ int t=getT(acc1, acc2, s); if (t==-1) continue; q.add(new int[]{t, s}); } // System.out.println(q); out.println(q.size()); while (!q.isEmpty()){ int[] v=q.poll(); out.println(v[0]+" "+v[1]); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
7fc701de8721efec19a9aca9defed54d
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class D { public static class Pair implements Comparable<Pair> { public int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair other) { if (Integer.compare(a, other.a) == 0) return Integer.compare(b, other.b); return Integer.compare(a, other.a); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = sc.nextInt(); List<Pair> results = new ArrayList<>(); int[] winsSoFar = new int[n+1], lossesSoFar = new int[n+1]; winsSoFar[0] = 0; lossesSoFar[0] = 0; for (int i = 1; i <= n; i++) { if (nums[i-1] == 1) { winsSoFar[i] = winsSoFar[i-1]+1; lossesSoFar[i] = lossesSoFar[i-1]; } else { winsSoFar[i] = winsSoFar[i-1]; lossesSoFar[i] = lossesSoFar[i-1]+1; } } for (int t = n; t >= 1; t--) { int pos = 0; int numWins = 0, numLosses = 0; boolean recentWin = false; boolean possible = true; while (pos < n) { if (pos + t > n) { possible = false; break; } int high = Math.min(pos + 2*t-1, n), low = pos + t; while (high >= low) { int mid = low + (high-low)/2; int wins = winsSoFar[mid]-winsSoFar[pos], losses = lossesSoFar[mid]-lossesSoFar[pos]; if (high == low) { if (wins == t) { numWins++; recentWin = true; pos = high; break; } else if (losses == t) { numLosses++; recentWin = false; pos = high; break; } else { possible = false; break; } } else if (high-low == 1 && wins == t) { numWins++; recentWin = true; pos = low; break; } else if (high-low == 1 && losses == t) { numLosses++; recentWin = false; pos = low; break; } else if (high-low == 1) { low = high; } else if (wins >= t || losses >= t) { high = mid; } else { low = mid; } } if (!possible) break; } if (possible && (numWins != numLosses)) { if ((numWins > numLosses && recentWin) || (numLosses > numWins & !recentWin)) results.add(new Pair(Math.max(numWins, numLosses), t)); } } Collections.sort(results); System.out.println(results.size()); for (Pair res: results) { System.out.println(res.a + " " + res.b); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
403f8f9f4b91916e5054480b63501857
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import static java.lang.Math.*; public class Solution implements Runnable { class Pair implements Comparable<Pair> { int x, y; Pair() { x = y = 0; } Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair p) { if (x != p.x) return x - p.x; else return y - p.y; } } void solve() throws Exception { int n = sc.nextInt(); int ps1[] = new int[n + 2]; int ps2[] = new int[n + 2]; for (int i = 0; i < n; i++) { int x = sc.nextInt(); ps1[i + 1] = ps1[i]; ps2[i + 1] = ps2[i]; if (x == 1) ps1[i + 1]++; else ps2[i + 1]++; } ps1[n + 1] = Integer.MAX_VALUE; ps2[n + 1] = Integer.MAX_VALUE; Pair ans[] = new Pair[n]; int m = 0; for (int t = 1; t <= n; t++) { int i = 0; int s[] = new int[2]; int lst = -1; while (i < n) { int lf = i, rg = n + 1; while (rg - lf > 1) { int md = (lf + rg) / 2; if (ps1[md] - ps1[i] >= t) rg = md; else lf = md; } int ni = rg; lf = i; rg = n + 1; while (rg - lf > 1) { int md = (lf + rg) / 2; if (ps2[md] - ps2[i] >= t) rg = md; else lf = md; } if (ni < rg) { s[0]++; lst = 0; } else { s[1]++; lst = 1; } ni = min(ni, rg); i = ni; } if (i == n && s[0] != s[1] && ((s[0] > s[1]) ^ (lst == 1))) { ans[m] = new Pair(max(s[0], s[1]), t); m++; } } Arrays.sort(ans, 0, m); out.println(m); for (int i = 0; i < m; i++) { out.println(ans[i].x + " " + ans[i].y); } } BufferedReader in; PrintWriter out; FastScanner sc; static Throwable throwable; public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); thread.run(); if (throwable != null) throw throwable; } public void run() { try { //in = new BufferedReader(new FileReader(".in")); //out = new PrintWriter(new FileWriter(".out")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Exception e) { throwable = e; } finally { out.close(); } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws Exception { while (strTok == null || !strTok.hasMoreTokens()) strTok = new StringTokenizer(reader.readLine()); return strTok.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
be9fc15a1a71fc9d3b28fb74f9446914
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class D { public static void main(String[] args) { int N = nextInt(); int INF = 1<<30; int pos[][] = new int[2][2*N + 1]; int sum[] = new int[N+1]; Arrays.fill(pos[0], INF); Arrays.fill(pos[1], INF); int count[] = new int[2]; Arrays.fill(count, 1); for(int i = 1; i <= N; i++) { int w = nextInt()-1; pos[w][count[w]] = i; count[w]++; sum[i] = sum[i-1] + w; } ArrayList<int[]> out = new ArrayList<int[]>(); L:for(int t = 1; t <= N; t++) { int set[] = new int[2]; if(pos[0][t] == INF && pos[1][t] == INF) continue; int i = -1; int finalWin = -1; if(pos[0][t] < pos[1][t]) { i = pos[0][t]; set[0]++; finalWin = 0; } else { i = pos[1][t]; set[1]++; finalWin = 1; } for(;i != N;) { int win1 = sum[i]; int win0 = i - sum[i]; if(pos[0][win0 + t] == INF && pos[1][win1 + t] == INF) { continue L; } if(pos[0][win0 + t] < pos[1][win1 + t]) { i = pos[0][win0 + t]; set[0]++; finalWin = 0; } else { i = pos[1][win1 + t]; set[1]++; finalWin = 1; } } if(set[0] == set[1]) { continue L; } if((set[0] > set[1] && finalWin == 0) || (set[1] > set[0] && finalWin == 1)) { out.add(new int[]{Math.max(set[0], set[1]), t}); } } if(out.isEmpty()) { System.out.println(0); } else { System.out.println(out.size()); Collections.sort(out, new Comparator<int[]>() { public int compare(int[] arg0, int[] arg1) { return arg0[0] == arg1[0] ? arg0[1] - arg1[1] : arg0[0] - arg1[0]; } }); for(int v[]: out) { System.out.println(v[0] +" "+ v[1]); } } } static int nextInt() { int c; try { c = System.in.read(); while(c != '-' && (c < '0' || c > '9')) c = System.in.read(); if(c == '-') return -nextInt(); int res = 0; while(c >= '0' && c <= '9') { res = res * 10 + c - '0'; c = System.in.read(); } return res; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
b0ce5c55a0323ca296f1312218a25783
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.*; import java.util.Map.Entry; public class D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] g = new int[n]; int[] f1 = new int[n+1]; int[] f2 = new int[n+1]; int[] t1 = new int[n]; int[] t2 = new int[n]; Arrays.fill(f1,-1); Arrays.fill(f2,-1); int c1 = 0; int c2 = 0; for (int i = 0; i<n; i++) { int x = scan.nextInt(); if (x == 1) { c1++; f1[c1] = i; } else { c2++; f2[c2] = i; } t1[i] = c1; t2[i] = c2; g[i] = x; } TreeMap<Integer,TreeSet<Integer>> set = new TreeMap<Integer,TreeSet<Integer>>(); int c = 0; for (int t = 1; t<=Math.max(c1,c2); t++) { int w1 = 0; int w2 = 0; int add1 = 0; int add2 = 0; while (true) { if (t1[n-1] < t+add1) { if (g[n-1] == 2 && (t2[n-1]-add2)%t == 0) { w2 += (t2[n-1]-add2)/t; if (w2>w1) { if (!set.containsKey(w2)) set.put(w2, new TreeSet<Integer>()); set.get(w2).add(t); c++; } } break; } else if (t2[n-1] < t+add2) { if (g[n-1] == 1 && (t1[n-1]-add1)%t == 0) { w1 += (t1[n-1]-add1)/t; if (w1>w2) { if (!set.containsKey(w1)) set.put(w1, new TreeSet<Integer>()); set.get(w1).add(t); c++; } } break; } int next1 = f1[t+add1]; int next2 = f2[t+add2]; if (next1 < next2) { w1++; add1 = t1[next1]; add2 = t2[next1]; } else { w2++; add1 = t1[next2]; add2 = t2[next2]; } } } System.out.println(c); for (Entry<Integer,TreeSet<Integer>> e: set.entrySet()) { for (int x : e.getValue()) { System.out.println(e.getKey() + " " + x); } } scan.close(); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
81b6583464e35aa394fd0c6defc9ead7
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> B = new ArrayList<Integer>(); ArrayList<Pair> ST = new ArrayList<Pair>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if(x==1) A.add(i); else B.add(i); } sc.close(); for (int i = 1; i <= n; i++) { int idx = -1; int pointA = 0,pointB = 0; while(idx<n-1) { int posA = Collections.binarySearch(A, idx); int posB = Collections.binarySearch(B, idx); if(posA<0) posA = Math.abs(posA+1); else if(idx==A.get(posA)) posA++; if(posB<0) posB = Math.abs(posB+1); else if(idx==B.get(posB)) posB++; int tA = posA+i-1; int tB = posB+i-1; if(tA>=A.size()&&tB>=B.size()) break; tA = posA+i-1>=A.size()?1000000:A.get(posA+i-1); tB = posB+i-1>=B.size()?1000000:B.get(posB+i-1); if(tA<tB) { pointA++; idx = tA; } else { pointB++; idx = tB; } } if(idx==n-1&&pointA!=pointB) { if(((pointA>pointB)&&A.get(A.size()-1)==idx)||((pointB>pointA)&&B.get(B.size()-1)==idx)) ST.add(new Pair(Math.max(pointA, pointB),i)); } } Collections.sort(ST); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); pw.println(ST.size()); for (int i = 0; i < ST.size(); i++) { pw.printf("%d %d\n",ST.get(i).S,ST.get(i).T); } pw.close(); } static class Pair implements Comparable<Pair> { int S,T; Pair(int a,int b) { S = a; T = b; } @Override public int compareTo(Pair o) { if(S==o.S) return this.T-o.T; return this.S-o.S; } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
03db6ab79c7977bc3a3088c3acb4efa4
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class D_Tennis_Game { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 300000); public static int n; public static int entrada[]; public static int arr1[]; // arr1[i] é o índice de entrada[] correspondente ao i-ésimo 1 public static int arr2[]; // arr2[i] é o índice de entrada[] correspondente ao i-ésimo 2 public static int arr1e2[][] = new int[3][100000]; // junção dos dois de cima public static int count[] = new int[3]; // count[1] é o número de 1's já lidos pela entrada e count[2] o [...] public static int arr1e2Inverso[][] = new int[3][100000]; // dado um índice do entrada, devolve um índice de arr1e2 public static void recebeEntrada() throws NumberFormatException, IOException { String[] nString = reader.readLine().trim().split("\\s+"); n = Integer.parseInt(nString[0]); entrada = new int[n]; String[] entradaString = reader.readLine().trim().split("\\s+"); count[1] = count[2] = -1; for (int i = 0; i < entradaString.length; i++) { entrada[i] = Integer.parseInt(entradaString[i]); arr1e2[entrada[i]][count[entrada[i]]+1] = i; arr1e2Inverso[1][i] = count[1] + 1; arr1e2Inverso[2][i] = count[2] + 1; count[entrada[i]]++; } count[1]++; // corrige a quantidade count[2]++; // corrige a quantidade } // Busca binária no vetor do perdedor para descobrir qual o próximo t-ésimo 1 ou t-ésimo 2 para servir de base // é quase o mesmo de saber quantos pontos foram desperdiçados na derrota public static int buscaIndiceBaseDoPerdedor(int perdedor, int entradaIndexDoVencedor) { return arr1e2Inverso[perdedor][entradaIndexDoVencedor]; } public static void solution() { int soma[] = {0, 0}; int somaVencedora; int NValidSolutions = 0; int [][]validSolutions = new int[1000000][2]; for (int k = 0; k < n; k++) { if (entrada[k] == 1) { soma[0]++; } else { soma[1]++; } } if (soma[0] > soma[1]) { somaVencedora = soma[0]; } else { somaVencedora = soma[1]; } for (int t = 1; t <= somaVencedora; t++) { int s = findS(t); if (s != 0){ // 0 se não encontrou, s se encontrou validSolutions[NValidSolutions][0] = s; validSolutions[NValidSolutions][1] = t; NValidSolutions++; } } // Fazendo a ordenação pelo s. Como é estável e o t foi inserido crescentemente, bate com o que o enunciado pede java.util.Arrays.sort(validSolutions, 0, NValidSolutions, new java.util.Comparator<int[]>() { public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); } }); System.out.println(NValidSolutions); for (int i = 0; i < NValidSolutions; i++) { System.out.println(validSolutions[i][0] + " " + validSolutions[i][1]); } } public static void solution_old() { int soma[] = {0, 0}; int somaVencedora; int NValidSolutions = 0; int [][]validSolutions = new int[1000000][2]; for (int k = 0; k < n; k++) { if (entrada[k] == 1) { soma[0]++; } else { soma[1]++; } } if (soma[0] > soma[1]) { somaVencedora = soma[0]; } else { somaVencedora = soma[1]; } for (int t = 1; t <= somaVencedora; t++) { int s = findS(t); if (s != 0){ // 0 se não encontrou, s se encontrou validSolutions[NValidSolutions][0] = s; validSolutions[NValidSolutions][1] = t; NValidSolutions++; } } // Fazendo a ordenação pelo s. Como é estável e o t foi inserido crescentemente, bate com o que o enunciado pede java.util.Arrays.sort(validSolutions, 0, NValidSolutions, new java.util.Comparator<int[]>() { public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); } }); System.out.println(NValidSolutions); for (int i = 0; i < NValidSolutions; i++) { System.out.println(validSolutions[i][0] + " " + validSolutions[i][1]); } } private static int findS(int t) { int []sets = {0, 0}; int base1 = 0, base2 = 0; int indice1, indice2; //while (t+base1 <= n && t+base2 <= n) { while (t+base1 <= count[1] || t+base2 <= count[2]) { if (t+base1 > count[1]) indice1 = 100001; else indice1 = arr1e2[1][t + base1-1]; //-1 pois arr1e2 começam no índice 0. O primeiro é o 0, o segundo é o 1, etc if (t+base2 > count[2]) indice2 = 100001; else indice2 = arr1e2[2][t + base2-1]; if (indice1 < indice2) { // 1 ganhou antes sets[0]++; base1 = t + base1; base2 = buscaIndiceBaseDoPerdedor(2, indice1); // parametros: perdedor e o índice do vencedor } else { // quem ganhou foi o 2 sets[1]++; base2 = t + base2; base1 = buscaIndiceBaseDoPerdedor(1, indice2); } } if (sets[0] != sets[1]) { if (sets[0] > sets[1]) { //if (1 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado, mas isso não é suficiente if (n-1 == arr1e2[1][base1-1]) { return sets[0]; } else return 0; } else { //if (2 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado if (n-1 == arr1e2[2][base2-1]) { return sets[1]; } else return 0; } } else return 0; } private static int findS_old(int t) { int []sets = {0, 0}; int []points = {0, 0}; for (int i = 0; i < n; i++) { if (entrada[i] == 1) { points[0]++; } else { points[1]++; } if (points[0] == t) { sets[0]++; points[0] = points[1] = 0; } else if (points[1] == t) { sets[1]++; points[0] = points[1] = 0; } } if (points[0] == 0 && points[1] == 0 && sets[0] != sets[1]) { if (sets[0] > sets[1]) { if (1 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado return sets[0]; } else return 0; } else { if (2 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado return sets[1]; } else return 0; } } else return 0; } public static void main(String []args) { try { recebeEntrada(); solution(); } catch (NumberFormatException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
fc06955589d063631b3d2792f21d7821
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //aasd public class D_Tennis_Game { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 300000); public static int n; public static int entrada[]; public static int arr1[]; // arr1[i] é o índice de entrada[] correspondente ao i-ésimo 1 public static int arr2[]; // arr2[i] é o índice de entrada[] correspondente ao i-ésimo 2 public static int arr1e2[][] = new int[3][100000]; // junção dos dois de cima public static int count[] = new int[3]; // count[1] é o número de 1's já lidos pela entrada e count[2] o [...] public static int arr1e2Inverso[][] = new int[3][100000]; // dado um índice do entrada, devolve um índice de arr1e2 public static void recebeEntrada() throws NumberFormatException, IOException { String[] nString = reader.readLine().trim().split("\\s+"); n = Integer.parseInt(nString[0]); entrada = new int[n]; String[] entradaString = reader.readLine().trim().split("\\s+"); count[1] = count[2] = -1; for (int i = 0; i < entradaString.length; i++) { entrada[i] = Integer.parseInt(entradaString[i]); arr1e2[entrada[i]][count[entrada[i]]+1] = i; arr1e2Inverso[1][i] = count[1] + 1; arr1e2Inverso[2][i] = count[2] + 1; count[entrada[i]]++; } count[1]++; // corrige a quantidade count[2]++; // corrige a quantidade } // Busca binária no vetor do perdedor para descobrir qual o próximo t-ésimo 1 ou t-ésimo 2 para servir de base // é quase o mesmo de saber quantos pontos foram desperdiçados na derrota public static int buscaIndiceBaseDoPerdedor(int perdedor, int entradaIndexDoVencedor) { return arr1e2Inverso[perdedor][entradaIndexDoVencedor]; } public static void solution() { int soma[] = {0, 0}; int somaVencedora; int NValidSolutions = 0; int [][]validSolutions = new int[1000000][2]; for (int k = 0; k < n; k++) { if (entrada[k] == 1) { soma[0]++; } else { soma[1]++; } } if (soma[0] > soma[1]) { somaVencedora = soma[0]; } else { somaVencedora = soma[1]; } for (int t = 1; t <= somaVencedora; t++) { int s = findS(t); if (s != 0){ // 0 se não encontrou, s se encontrou validSolutions[NValidSolutions][0] = s; validSolutions[NValidSolutions][1] = t; NValidSolutions++; } } // Fazendo a ordenação pelo s. Como é estável e o t foi inserido crescentemente, bate com o que o enunciado pede java.util.Arrays.sort(validSolutions, 0, NValidSolutions, new java.util.Comparator<int[]>() { public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); } }); System.out.println(NValidSolutions); for (int i = 0; i < NValidSolutions; i++) { System.out.println(validSolutions[i][0] + " " + validSolutions[i][1]); } } public static void solution_old() { int soma[] = {0, 0}; int somaVencedora; int NValidSolutions = 0; int [][]validSolutions = new int[1000000][2]; for (int k = 0; k < n; k++) { if (entrada[k] == 1) { soma[0]++; } else { soma[1]++; } } if (soma[0] > soma[1]) { somaVencedora = soma[0]; } else { somaVencedora = soma[1]; } for (int t = 1; t <= somaVencedora; t++) { int s = findS(t); if (s != 0){ // 0 se não encontrou, s se encontrou validSolutions[NValidSolutions][0] = s; validSolutions[NValidSolutions][1] = t; NValidSolutions++; } } // Fazendo a ordenação pelo s. Como é estável e o t foi inserido crescentemente, bate com o que o enunciado pede java.util.Arrays.sort(validSolutions, 0, NValidSolutions, new java.util.Comparator<int[]>() { public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); } }); System.out.println(NValidSolutions); for (int i = 0; i < NValidSolutions; i++) { System.out.println(validSolutions[i][0] + " " + validSolutions[i][1]); } } private static int findS(int t) { int []sets = {0, 0}; int base1 = 0, base2 = 0; int indice1, indice2; //while (t+base1 <= n && t+base2 <= n) { while (t+base1 <= count[1] || t+base2 <= count[2]) { if (t+base1 > count[1]) indice1 = 100001; else indice1 = arr1e2[1][t + base1-1]; //-1 pois arr1e2 começam no índice 0. O primeiro é o 0, o segundo é o 1, etc if (t+base2 > count[2]) indice2 = 100001; else indice2 = arr1e2[2][t + base2-1]; if (indice1 < indice2) { // 1 ganhou antes sets[0]++; base1 = t + base1; base2 = buscaIndiceBaseDoPerdedor(2, indice1); // parametros: perdedor e o índice do vencedor } else { // quem ganhou foi o 2 sets[1]++; base2 = t + base2; base1 = buscaIndiceBaseDoPerdedor(1, indice2); } } if (sets[0] != sets[1]) { if (sets[0] > sets[1]) { //if (1 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado, mas isso não é suficiente if (n-1 == arr1e2[1][base1-1]) { return sets[0]; } else return 0; } else { //if (2 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado if (n-1 == arr1e2[2][base2-1]) { return sets[1]; } else return 0; } } else return 0; } private static int findS_old(int t) { int []sets = {0, 0}; int []points = {0, 0}; for (int i = 0; i < n; i++) { if (entrada[i] == 1) { points[0]++; } else { points[1]++; } if (points[0] == t) { sets[0]++; points[0] = points[1] = 0; } else if (points[1] == t) { sets[1]++; points[0] = points[1] = 0; } } if (points[0] == 0 && points[1] == 0 && sets[0] != sets[1]) { if (sets[0] > sets[1]) { if (1 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado return sets[0]; } else return 0; } else { if (2 == entrada[n-1]) { // o vencedor tem que ser o último a ter jogado return sets[1]; } else return 0; } } else return 0; } public static void main(String []args) { try { recebeEntrada(); solution(); } catch (NumberFormatException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
2f297bc41e4f4948870edf59d2fe3900
train_001.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final int MOD = (int)(1e9 + 7); private int n; private int[] a; private int[] sum1; private int[] sum2; private ArrayList<Integer> win1; private ArrayList<Integer> win2; private ArrayList<int[]> ans; public void test(int t) { int pre = 0; int cnt1 = 0, cnt2 = 0; while(true) { if(pre == n) { break; } if(sum1[pre] + t > sum1[n] && sum2[pre] + t > sum2[n]) { return; } int index1 = Integer.MAX_VALUE; if(sum1[pre] + t <= sum1[n]) { index1 = win1.get(sum1[pre] + t); } int index2 = Integer.MAX_VALUE; if(sum2[pre] + t <= sum2[n]) { index2 = win2.get(sum2[pre] + t); } if(index1 < index2) { ++cnt1; pre = index1; } else { ++cnt2; pre = index2; } } if(cnt1 > cnt2 && 1 == a[n]) { ans.add(new int[]{cnt1, t}); } else if(cnt1 < cnt2 && 2 == a[n]) { ans.add(new int[]{cnt2, t}); } } public void foo() { n = scan.nextInt(); a = new int[n + 1]; sum1 = new int[n + 1]; sum2 = new int[n + 1]; win1 = new ArrayList<Integer>(); win2 = new ArrayList<Integer>(); win1.add(0); win2.add(0); for(int i = 1;i <= n;++i) { a[i] = scan.nextInt(); sum1[i] = sum1[i - 1]; sum2[i] = sum2[i - 1]; if(1 == a[i]) { ++sum1[i]; win1.add(i); } else { ++sum2[i]; win2.add(i); } } ans = new ArrayList<int[]>(); for(int i = 1;i <= n;++i) { test(i); } Collections.sort(ans, new Comparator<int[]>() { public int compare(int[] a, int [] b) { if(a[0] != b[0]) { return a[0] - b[0]; } else { return a[1] - b[1]; } } }); out.println(ans.size()); for(int[] a : ans) { out.println(a[0] + " " + a[1]); } } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 & 15; 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 & 15) * m; c = read(); } } return res * sgn; } public String next() { 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 boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 7
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
fba5317bf1ea1f9b85f909419c4e56ee
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.TreeSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author DY */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.readInt(); Day[] days = new Day[N]; for (int i = 0; i < N; ++i) { days[i] = new Day(in.readInt(), i); } if (N == 1) { out.printLine(days[0].speed + 1); return; } Arrays.sort(days, new Comparator<Day>() { public int compare(Day o1, Day o2) { return o1.speed - o2.speed; } }); TreeSet<Interval> intervals = new TreeSet<>(Interval.LEFT_ENDPOINT_ORDER); CountMap counts = new CountMap(); int max = 0; int min = -1; for (int i = 1; i < N; ++i) { if (days[i - 1].speed == days[i].speed) continue; Interval pre = new Interval(days[i - 1].index, days[i - 1].index + 1); Interval[] border = {intervals.lower(pre), intervals.higher(pre)}; for (int b = 0; b < 2; ++b) { if (border[b] != null && border[b].intersects(pre)) { throw new RuntimeException(); } } if (border[0] != null && border[1] != null && border[0].right() + 1 == border[1].left()) { for (int b = 0; b < 2; ++b) { intervals.remove(border[b]); counts.decrease(border[b].length()); } intervals.add(new Interval(border[0].left(), border[1].right())); counts.increase(border[0].length() + 1 + border[1].length()); } else { boolean joined = false; for (int b = 0; b < 2; ++b) { if (border[b] != null && (b == 0 ? border[b].right() == pre.left() : pre.right() == border[b].left())) { if (joined) { throw new RuntimeException(); } intervals.remove(border[b]); intervals.add(new Interval(Math.min(border[b].left(), pre.left()), Math.max(border[b].right(), pre.right()))); counts.decrease(border[b].length()); counts.increase(border[b].length() + 1); joined = true; } } if (!joined) { intervals.add(pre); counts.increase(1); } } if (counts.size() == 1) { int count = counts.value(); if (count > max) { max = count; min = days[i - 1].speed + 1; } } } out.printLine(min); } class CountMap { HashMap<Integer, Integer> map = new HashMap<>(); void increase(int key) { map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1); } void decrease(int key) { if (!map.containsKey(key)) { throw new RuntimeException(); } int nc = map.get(key) - 1; if (nc == 0) map.remove(key); else map.put(key, nc); } int size() { return map.size(); } int value() { return map.values().toArray(new Integer[0])[0]; } } class Day { int speed; int index; public Day(int speed, int index) { this.speed = speed; this.index = index; } } } 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 printLine(int i) { writer.println(i); } } static class Interval implements Comparable<Interval> { public static final Comparator<Interval> LEFT_ENDPOINT_ORDER = new Interval.LeftComparator(); public static final Comparator<Interval> LENGTH_ORDER = new Interval.LengthComparator(); int left; int right; public Interval() { } public Interval(int left, int right) { if (left <= right) { this.left = left; this.right = right; } else throw new IllegalArgumentException("Illegal interval"); } public int left() { return left; } public int right() { return right; } public boolean intersects(Interval that) { if (this.right <= that.left) return false; if (that.right <= this.left) return false; return true; } public int length() { return right - left; } public String toString() { return "[" + left + ", " + right + "]"; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Interval that = (Interval) o; if (left != that.left) return false; return right == that.right; } public int hashCode() { int result = left; result = 31 * result + right; return result; } public int compareTo(Interval o) { return LENGTH_ORDER.compare(this, o); } private static class LeftComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { if (a.left < b.left) return -1; else if (a.left > b.left) return +1; else if (a.right < b.right) return -1; else if (a.right > b.right) return +1; else return 0; } } private static class LengthComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { double alen = a.length(); double blen = b.length(); if (alen > blen) return +1; else if (alen < blen) return -1; else return a.left - b.left; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
e77aaf4c58a9f9ea0ba9b33a9dd4d83d
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class Shark { static int mod = 1000000007; static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int n; static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair p) { return this.x-p.x; } } static Pair[] a; static int[] parent; static int[] size; static boolean[] visited; static Map<Integer, Integer> map; static int connected=0; public static int getroot(int v) { while(parent[v]!=v) { v=parent[v]; parent[v]=parent[parent[v]]; } return v; } public static void merge(int x,int y) { int u=getroot(x); int v=getroot(y); if(u==v) return; connected--; if(map.containsKey(size[u])) map.put(size[u], map.get(size[u])-1); if(map.containsKey(size[v])) map.put(size[v], map.get(size[v])-1); if(map.containsKey(size[u])&&map.get(size[u])<=0) { map.remove(size[u]); } if(map.containsKey(size[v])&&map.get(size[v])<=0) { map.remove(size[v]); } if(map.containsKey(size[u]+size[v])) map.put(size[u]+size[v], map.get(size[u]+size[v])+1); else map.put(size[u]+size[v], 1); if(size[u]>size[v]) { parent[v]=u; size[u]+=size[v]; size[v]=0; } else { parent[u]=v; size[v]+=size[u]; size[u]=0; } } public static void main(String[] args) { n=in.nextInt(); a=new Pair[n]; parent=new int[n+1]; size=new int[n+1]; visited=new boolean[n+2]; map=new HashMap<>(); for(int i=1;i<=n;i++) { parent[i]=i; size[i]=1; } for(int i=0;i<n;i++) { int x=in.nextInt(); a[i]=new Pair(x, i+1); } Arrays.sort(a); int comp=1; int ans=a[0].x+1; for(int i=0;i<n;i++) { int idx=a[i].y; connected++; visited[idx]=true; if(map.containsKey(1)) map.put(1, map.get(1)+1); else map.put(1, 1); if(idx+1<=n&&visited[idx+1]) { merge(idx, idx+1); } if(idx-1>=1&&visited[idx-1]) { merge(idx, idx-1); } if(map.size()==1) { if(connected>comp) { comp=connected; ans=a[i].x+1; } } } out.println(ans); out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } private static void tr(Object... o) { if (!(System.getProperty("ONLINE_JUDGE") != null)) System.out.println(Arrays.deepToString(o)); } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
333c6324bc90702050af87df61aeeb27
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class D { FastScanner scanner; PrintWriter writer; void solve() throws IOException { scanner = new FastScanner(System.in); writer = new PrintWriter(System.out); int n = scanner.nextInt(); int[] as = new int[n]; Day[] days = new Day[n]; for (int i = 0; i < n; i++) { as[i] = scanner.nextInt(); days[i] = new Day(i, as[i]); } Arrays.sort(days); Dsu dsu = new Dsu(n); int locs = 0; int[] streaks = new int[n + 1]; int maxLocs = 0; int maxK = 0; for (Day day : days) { int i = day.i; int k = day.a + 1; if (i > 0 && as[i - 1] < k) { locs--; streaks[dsu.size(i - 1)]--; dsu.union(i, i - 1); } if (i < n - 1 && as[i + 1] < k) { locs--; streaks[dsu.size(i + 1)]--; dsu.union(i, i + 1); } locs++; streaks[dsu.size(i)]++; if (streaks[dsu.size(i)] == locs && locs > maxLocs) { maxLocs = locs; maxK = k; } } writer.println(maxK); writer.close(); } static class Day implements Comparable<Day> { int i; int a; public Day(int i, int a) { this.i = i; this.a = a; } @Override public int compareTo(Day o) { return Integer.compare(a, o.a); } } static class Dsu { int[] rank; int[] parent; int[] size; Dsu(int n) { this.rank = new int[n]; this.parent = new int[n]; this.size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } int get(int v) { if (v == parent[v]) return v; else return parent[v] = get(parent[v]); } void union(int a, int b) { a = get(a); b = get(b); if (a != b) { if (rank[a] < rank[b]) { int tmp = a; a = b; b = tmp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; size[a] += size[b]; } } int size(int v) { return size[get(v)]; } } public static void main(String[] args) throws IOException { new D().solve(); } static class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(InputStream is) { this.br = new BufferedReader(new InputStreamReader(is)); } FastScanner(File file) throws FileNotFoundException { this(new FileInputStream(file)); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(br.readLine()); return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
ab4efeca4ab4a21ed758fd5dfcd9d34e
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; public class Shark { public static class Node { boolean loc = false; int count = 1; Node left = null; Node right = null; } public static void main (String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String[] sp = in.readLine().split(" "); Node last = null; int[] arr = new int[n]; Map<Integer, Node> nodeMap = new HashMap<>(); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(sp[i]); Node node = new Node(); if (i > 0) { node.left = last; last.right = node; } last = node; nodeMap.put(arr[i], node); } Arrays.sort(arr); int best = 0; int bk = 0; Map<Integer, Integer> locCount = new HashMap<>(); for (int i = 0; i < n; i++) { Node node = nodeMap.get(arr[i]); node.loc = true; if (node.left != null && node.left.loc) { locCount.put(node.left.count, locCount.get(node.left.count) -1); if (locCount.get(node.left.count) == 0) { locCount.remove(node.left.count); } node.count += node.left.count; if (node.left.left != null) node.left.left.right = node; node.left = node.left.left; } if (node.right != null && node.right.loc) { locCount.put(node.right.count, locCount.get(node.right.count) -1); if (locCount.get(node.right.count) == 0) { locCount.remove(node.right.count); } node.count += node.right.count; if (node.right.right != null) node.right.right.left = node; node.right = node.right.right; } int cnt = locCount.containsKey(node.count) ? locCount.get(node.count) : 0; locCount.put(node.count, cnt + 1); if (locCount.size() == 1) { int val = locCount.values().iterator().next(); if (val > best) { best = val; bk = arr[i]; } } } System.out.println(bk + 1); } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
8fbfedcd119df7a535a54bfc2c271628
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
//package contests.CF484; import java.io.*; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); Pair[] values = new Pair[n]; int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); values[i] = new Pair(i, arr[i]); } Arrays.sort(values); boolean[] valid = new boolean[n]; UnionFind groups = new UnionFind(n); HashMap<Integer, Integer> map = new HashMap<>(); int maxLoc = 0; int val = Integer.MAX_VALUE; for (int i = 0; i < values.length; i++) { if(map.size() == 1) { int curLoc = 0; for (int ll: map.keySet()) curLoc = map.get(ll); if(curLoc > maxLoc) { maxLoc = curLoc; val = values[i].val; } else if(curLoc == maxLoc) { val = Math.min(val, values[i].val); } } int left = -1; int right = -1; int idx = values[i].idx; if(idx > 0 && valid[idx-1]) { left = groups.sizeOfSet(idx - 1); groups.unionSet(idx, idx-1); } if(idx < n-1 && valid[idx+1]) { right = groups.sizeOfSet(idx + 1); groups.unionSet(idx, idx+1); } // remove left if(left != -1) { int occ = map.remove(left)-1; if(occ > 0) map.put(left, occ); } // remove right if(right != -1) { int occ = map.remove(right)-1; if(occ > 0) map.put(right, occ); } // add element map.put(groups.sizeOfSet(idx), map.getOrDefault(groups.sizeOfSet(idx), 0) + 1); // System.err.println(map); // System.err.println("==============="); valid[idx] = true; } int maxSmallest = -1; for (int j = 0; j < n; j++) { if(arr[j] < val) maxSmallest = Math.max(maxSmallest, arr[j]); } pw.println(Math.min(maxSmallest+1, val)); pw.flush(); pw.close(); } static class Pair implements Comparable<Pair> { int idx, val; public Pair(int idx, int val) { this.idx = idx; this.val = val; } @Override public int compareTo(Pair p) { return val - p.val; } public String toString() { return idx + " " + val; } } static class UnionFind { int[] p, rank, setSize; int numSets; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if(rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
b9fa97530ceb80af749d078dca423c1b
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.Arrays; import java.util.TreeMap; import java.util.HashMap; import java.util.Comparator; import java.util.TreeSet; import java.util.Collection; import java.lang.Iterable; public class Task { public static int getOrDefault(HashMap<Integer, Integer> map, int key, int def) { if (!map.containsKey(key)) return def; return map.get(key); } public static void main(String args[]) { Scanner in = new Scanner(System.in); int n; int maxk; //final Pair [] a; HashMap<Integer, Integer> intervals = new HashMap<Integer, Integer>(); TreeSet<Integer> keyIntervals = new TreeSet<Integer>(); HashMap<Integer, Integer> intervalSizes = new HashMap<Integer, Integer>(); int k; n = in.nextInt(); //System.out.println("n: " + n); Pair [] a = new Pair[n]; //System.out.println("a: " + a); for (int i = 0; i < n; i++) { a[i] = new Pair(in.nextInt(), i); } Arrays.sort(a, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.a - p2.a; } }); //for (int i = 0; i < n; i++) // System.out.println(a[i].a + " "); /* init */ k = a[n - 1].a + 1; maxk = 1; keyIntervals.add(-1); intervals.put(-1, n + 1); intervalSizes.put(n + 1, getOrDefault(intervalSizes, n + 1, 0) + 1); for (int i = n - 1; i > 0; i--) { int rootKey = a[i].pos; int lowerKey = keyIntervals.lower(rootKey); int lowerSize = intervals.get(lowerKey); int upperKey = lowerKey + lowerSize; //System.out.println("Lower: " + lowerKey); intervalSizes.put(lowerSize, getOrDefault(intervalSizes, lowerSize, 0) - 1); /* TODO */ if (intervalSizes.get(lowerSize) <= 0) { intervalSizes.remove(lowerSize); } intervals.remove(lowerKey); keyIntervals.remove(lowerKey); int leftKey = lowerKey; int leftSize = rootKey - lowerKey; int rootSize = upperKey - rootKey; //System.out.println("root interval: " + rootKey + " " + rootSize); if (rootSize > 1) { keyIntervals.add(rootKey); intervalSizes.put(rootSize, getOrDefault(intervalSizes, rootSize, 0) + 1); intervals.put(rootKey, rootSize); } //System.out.println("left interval: " + leftKey + " " + leftSize); if (leftSize > 1) { keyIntervals.add(leftKey); intervalSizes.put(leftSize, getOrDefault(intervalSizes, leftSize, 0) + 1); intervals.put(leftKey, leftSize); } if (intervalSizes.size() == 1 && intervalSizes.values().iterator().next() >= maxk) { /* all days are equal */ Collection<Integer> values = intervalSizes.values(); maxk = intervalSizes.values().iterator().next(); //System.out.println(values); k = a[i - 1].a + 1; } //System.out.println("Different sizes: " + intervalSizes.size()); //System.out.println("Sizes: " + intervalSizes); } System.out.println(k); } } class Pair { public int a, pos; public Pair(int a, int pos) { this.a = a; this.pos = pos; } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
d337c18c413851408e9efa879ce39f2c
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; public class CODEFORCES { @SuppressWarnings("rawtypes") static InputReader in; static PrintWriter out; static int mx = Integer.MAX_VALUE - 1000000; public static class SegmentTree { int n; int arr[], lazy[]; SegmentTree(int n) { this.n = n; arr = new int[n << 2]; Arrays.fill(arr, mx); lazy = new int[n << 2]; } SegmentTree(int a[]) { this.n = a.length; arr = new int[n << 2]; lazy = new int[n << 2]; build(0, n - 1, 0, a); } void build(int l, int r, int c, int a[]) { if (l == r) { arr[c] = a[l]; return; } int mid = l + r >> 1; build(l, mid, (c << 1) + 1, a); build(mid + 1, r, (c << 1) + 2, a); arr[c] = merge(arr[(c << 1) + 1], arr[(c << 1) + 2]); } int merge(int a, int b) { return Math.min(a, b); } int lazymerge(int a, int b) { return b; } boolean getInitialValue(long a) { return !(a == 0); } void check(int c, int l, int r) { if (getInitialValue(lazy[c])) { arr[c] = lazymerge(arr[c], lazy[c]); if (l != r) { lazy[(c << 1) + 1] = lazymerge(lazy[(c << 1) + 1], lazy[c]); lazy[(c << 1) + 2] = lazymerge(lazy[(c << 1) + 2], lazy[c]); } lazy[c] = 0; } } void update(int l, int r, int c, int x, int y, int val) { check(c, l, r); if (l > r || x > y || l > y || x > r) return; if (x <= l && y >= r) { arr[c] = lazymerge(arr[c], val); if (l != r) { lazy[(c << 1) + 1] = lazymerge(lazy[(c << 1) + 1], val); lazy[(c << 1) + 2] = lazymerge(lazy[(c << 1) + 2], val); } return; } int mid = l + r >> 1; update(l, mid, (c << 1) + 1, x, y, val); update(mid + 1, r, (c << 1) + 2, x, y, val); arr[c] = merge(arr[(c << 1) + 1], arr[(c << 1) + 2]); } void up(int x, int y, int val) { update(0, n - 1, 0, x, y, val); } int get(int l, int r, int c, int x, int y) { check(c, l, r); if (l > r || x > y || l > y || x > r) // return inverse value return mx; else if (x <= l && y >= r) return arr[c]; int mid = l + r >> 1; return merge(get(l, mid, (c << 1) + 1, x, y), get(mid + 1, r, (c << 1) + 2, x, y)); } int ans(int x, int y) { return get(0, n - 1, 0, x, y); } } public static class SegmentTree2 { int n; int arr[], lazy[]; SegmentTree2(int n) { this.n = n; arr = new int[n << 2]; lazy = new int[n << 2]; } SegmentTree2(int a[]) { this.n = a.length; arr = new int[n << 2]; lazy = new int[n << 2]; build(0, n - 1, 0, a); } void build(int l, int r, int c, int a[]) { if (l == r) { arr[c] = a[l]; return; } int mid = l + r >> 1; build(l, mid, (c << 1) + 1, a); build(mid + 1, r, (c << 1) + 2, a); arr[c] = merge(arr[(c << 1) + 1], arr[(c << 1) + 2]); } int merge(int a, int b) { return Math.max(a, b); } int lazymerge(int a, int b) { return b; } boolean getInitialValue(long a) { return !(a == 0); } void check(int c, int l, int r) { if (getInitialValue(lazy[c])) { arr[c] = lazymerge(arr[c], lazy[c]); if (l != r) { lazy[(c << 1) + 1] = lazymerge(lazy[(c << 1) + 1], lazy[c]); lazy[(c << 1) + 2] = lazymerge(lazy[(c << 1) + 2], lazy[c]); } lazy[c] = 0; } } void update(int l, int r, int c, int x, int y, int val) { check(c, l, r); if (l > r || x > y || l > y || x > r) return; if (x <= l && y >= r) { arr[c] = lazymerge(arr[c], val); if (l != r) { lazy[(c << 1) + 1] = lazymerge(lazy[(c << 1) + 1], val); lazy[(c << 1) + 2] = lazymerge(lazy[(c << 1) + 2], val); } return; } int mid = l + r >> 1; update(l, mid, (c << 1) + 1, x, y, val); update(mid + 1, r, (c << 1) + 2, x, y, val); arr[c] = merge(arr[(c << 1) + 1], arr[(c << 1) + 2]); } void up(int x, int y, int val) { update(0, n - 1, 0, x, y, val); } int get(int l, int r, int c, int x, int y) { check(c, l, r); if (l > r || x > y || l > y || x > r) // return inverse value return 0; else if (x <= l && y >= r) return arr[c]; int mid = l + r >> 1; return merge(get(l, mid, (c << 1) + 1, x, y), get(mid + 1, r, (c << 1) + 2, x, y)); } int ans(int x, int y) { return get(0, n - 1, 0, x, y); } } /* * public class SegmentTree3 { int n; int arr[], lazy[]; * * SegmentTree3(int n) { this.n = n; arr = new int[n << 2]; lazy = new int[n << * 2]; } * * SegmentTree3(int a[]) { this.n = a.length; arr = new int[n << 2]; lazy = new * int[n << 2]; build(0, n - 1, 0, a); } * * void build(int l, int r, int c, int a[]) { if (l == r) { arr[c] = a[l]; * return; } int mid = l + r >> 1; build(l, mid, (c << 1) + 1, a); build(mid + * 1, r, (c << 1) + 2, a); arr[c] = merge(arr[(c << 1) + 1], arr[(c << 1) + 2]); * } * * int merge(int a, int b) { return a + b; } * * int lazymerge(int a, int b) { return b; } * * boolean getInitialValue(long a) { return !(a == 0); } * * void check(int c, int l, int r) { if (getInitialValue(lazy[c])) { arr[c] = * lazymerge(arr[c], lazy[c]); if (l != r) { lazy[(c << 1) + 1] = * lazymerge(lazy[(c << 1) + 1], lazy[c]); lazy[(c << 1) + 2] = * lazymerge(lazy[(c << 1) + 2], lazy[c]); } lazy[c] = 0; } } * * void update(int l, int r, int c, int x, int y, int val) { check(c, l, r); if * (l > r || x > y || l > y || x > r) return; if (x <= l && y >= r) { arr[c] = * lazymerge(arr[c], val); if (l != r) { lazy[(c << 1) + 1] = lazymerge(lazy[(c * << 1) + 1], val); lazy[(c << 1) + 2] = lazymerge(lazy[(c << 1) + 2], val); } * return; } int mid = l + r >> 1; update(l, mid, (c << 1) + 1, x, y, val); * update(mid + 1, r, (c << 1) + 2, x, y, val); arr[c] = merge(arr[(c << 1) + * 1], arr[(c << 1) + 2]); } * * void up(int x, int y, int val) { update(0, n - 1, 0, x, y, val); } * * int get(int l, int r, int c, int x, int y) { check(c, l, r); if (l > r || x > * y || l > y || x > r) // return inverse value return 0; else if (x <= l && y * >= r) return arr[c]; int mid = l + r >> 1; return merge(get(l, mid, (c << 1) * + 1, x, y), get(mid + 1, r, (c << 1) + 2, x, y)); } * * int ans(int x, int y) { return get(0, n - 1, 0, x, y); } } */ static void solve() { int n = in.ni(); int arr[] = new int[n + 1]; int tmp[] = new int[3 * n]; int cnt = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); Pair p[] = new Pair[n]; for (int i = 1; i <= n; i++) { arr[i] = in.ni(); p[i - 1] = new Pair(arr[i], i); tmp[cnt++] = arr[i] - 1; tmp[cnt++] = arr[i]; tmp[cnt++] = arr[i] + 1; } Arrays.parallelSort(tmp); Arrays.parallelSort(p); SegmentTree seg = new SegmentTree(n + 10); SegmentTree2 seg2 = new SegmentTree2(n + 10); int cnt2 = 0; int ans = mx; int nm = 0, ans2 = 0; for (int i = 0; i < cnt; i++) { while (cnt2 < n && p[cnt2].u < tmp[i]) { // debug(i, cnt2, tmp[i], nm); int ind = (int) p[cnt2].v; int min = ind; int max = ind; min = Math.min(seg.ans(ind - 1, ind - 1), min); max = Math.max(max, seg2.ans(ind + 1, ind + 1)); if (min != ind && max != ind) { int length = max - min + 1; map.put(ind - min, map.get(ind - min) - 1); if (map.get(ind - min) == 0) map.remove(ind - min); map.put(max - ind, map.get(max - ind) - 1); if (map.get(max - ind) == 0) map.remove(max - ind); if (map.containsKey(length)) map.put(length, map.get(length) + 1); else map.put(length, 1); seg.up(min, max, min); seg2.up(min, max, max); nm--; } else if (min != ind) { int length = ind - min + 1; map.put(ind - min, map.get(ind - min) - 1); if (map.get(ind - min) == 0) map.remove(ind - min); if (map.containsKey(length)) map.put(length, map.get(length) + 1); else map.put(length, 1); seg.up(min, ind, min); seg2.up(min, ind, ind); // debug(i); } else if (max != ind) { int length = max - ind + 1; map.put(max - ind, map.get(max - ind) - 1); if (map.get(max - ind) == 0) map.remove(max - ind); if (map.containsKey(length)) map.put(length, map.get(length) + 1); else map.put(length, 1); seg.up(ind, max, ind); seg2.up(ind, max, max); // debug(i); } else { int length = max - min + 1; if (map.containsKey(length)) map.put(length, map.get(length) + 1); else map.put(length, 1); seg.up(min, max, min); seg2.up(min, max, max); nm++; // debug(nm); } cnt2++; } if (map.size() == 1) { if (ans2 < nm) { ans = tmp[i]; ans2 = nm; } } } out.println(ans); } public static class Pair implements Comparable<Pair> { long u; long v; public Pair(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return u + " " + v; } } static int[][] graph(int from[], int to[], int n, int cn) { int g[][] = new int[n][]; int cnt[] = new int[n]; for (int i = 0; i < cn; i++) { cnt[from[i]]++; // cnt[to[i]]++; } for (int i = 0; i < n; i++) g[i] = new int[cnt[i]]; Arrays.fill(cnt, 0); for (int i = 0; i < cn; i++) { g[from[i]][cnt[from[i]]++] = to[i]; // g[to[i]][cnt[to[i]]++] = from[i]; } return g; } @SuppressWarnings("rawtypes") static void soln() { in = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { try { soln(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } // To Get Input // Some Buffer Methods static class InputReader<SpaceCharFilter> { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
9800e989b45c475ad18f727e6125eb4c
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; static int mod = 1_000_000_007; static int[] di = {-1, 1, 0, 0}; static int[] dj = {0, 0, -1, 1}; static int[] par, sz; public static void main(String[] args) throws IOException { int n = in.nextInt(); Pair[] p = new Pair[n]; for(int i = 0; i < n; ++i) { p[i] = new Pair(in.nextInt(), i); } Arrays.sort(p); int numComp = 0; par = new int[n]; sz = new int[n]; for(int i = 0; i < n; ++i) par[i] = i; boolean[] include = new boolean[n]; Map<Integer, Integer> sizes = new HashMap<>(); int best = -1, ans = -1; for(int i = 0; i < n; ++i) { int value = p[i].first; int idx = p[i].second; if(idx-1 >= 0 && include[idx-1]) { numComp--; int old = find(idx-1); update(sizes, sz[old], -1); merge(idx, idx-1); } if(idx+1 < n && include[idx+1]) { numComp--; int old = find(idx+1); update(sizes, sz[old], -1); merge(idx, idx+1); } numComp++; include[idx] = true; update(sizes, ++sz[find(idx)], 1); if(sizes.size() == 1 && numComp > best) { best = numComp; ans = value + 1; } } System.out.println(ans); out.close(); } static void update(Map<Integer, Integer> sizes, int k, int v) { int x = sizes.getOrDefault(k, 0); x += v; if(x == 0) sizes.remove(k); else sizes.put(k, x); } static int find(int x) { return par[x] == x ? x : (par[x] = find(par[x])); } static void merge(int x, int y) { x = find(x); y = find(y); if(x == y) return; par[x] = y; sz[y] += sz[x]; } static class SegmentTree { int n; long[] a, seg; int DEFAULT_VALUE = 0; public SegmentTree(long[] a, int n) { super(); this.a = a; this.n = n; seg = new long[n * 4 + 1]; build(1, 0, n-1); } private long build(int node, int i, int j) { if(i == j) return seg[node] = a[i]; long first = build(node * 2, i, (i+j) / 2); long second = build(node * 2 + 1, (i+j) / 2 + 1, j); return seg[node] = combine(first, second); } long update(int k, long value) { return update(1, 0, n-1, k, value); } private long update(int node, int i, int j, int k, long value) { if(k < i || k > j) return seg[node]; if(i == j && j == k) { a[k] = value; seg[node] = value; return value; } int m = (i + j) / 2; long first = update(node * 2, i, m, k, value); long second = update(node * 2 + 1, m + 1, j, k, value); return seg[node] = combine(first, second); } long query(int l, int r) { return query(1, 0, n-1, l, r); } private long query(int node, int i, int j, int l, int r) { if(l <= i && j <= r) return seg[node]; if(j < l || i > r) return DEFAULT_VALUE; int m = (i + j) / 2; long first = query(node * 2, i, m, l, r); long second = query(node * 2 + 1, m+1, j, l, r); return combine(first, second); } private long combine(long a, long b) { return a + b; } } static class DisjointSet { int n; int[] g; int[] h; public DisjointSet(int n) { super(); this.n = n; g = new int[n]; h = new int[n]; for(int i = 0; i < n; ++i) { g[i] = i; h[i] = 1; } } int find(int x) { if(g[x] == x) return x; return g[x] = find(g[x]); } void union(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(h[x] >= h[y]) { g[y] = x; if(h[x] == h[y]) h[x]++; } else { g[x] = y; } } } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } // @Override // public int compareTo(Pair o) { // return this.first != o.first ? o.first - this.first : o.second - this.second; // } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
3716a3f3de70e01866176e20d70623f1
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid to fall... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) public class Main { public static void main(String[] args) { int n=ni(); int[]a=nia(n); Integer[]pos=new Integer[n]; for(int i=0; i<n; i++) pos[i]=i; Arrays.sort(pos, new Comparator<Integer>() { public int compare(Integer c, Integer d) { if(a[c]>a[d]) return 1; else if(a[d]>a[c]) return -1; return 0; } }); NavigableMap<Integer, Integer> ho=new TreeMap<Integer, Integer>(); ho.put(0, n-1); Map<Integer, Integer> hola=new HashMap<Integer, Integer>(); hola.put(n,1); int ans=1,val=a[pos[n-1]]+1; for(int i=n-2; i>=0; i--) { int po=pos[i+1]; int lol=ho.floorKey(po); int temp=ho.get(lol); if(lol==po&&po==temp) { ho.remove(lol); if(!hola.remove(1,1)) hola.put(1, hola.get(1)-1); } else if(lol==po) { ho.remove(lol); ho.put(lol+1,temp); if(!hola.remove(temp-lol+1,1)) hola.put(temp-lol+1, hola.get(temp-lol+1)-1); hola.put(temp-lol, hola.getOrDefault(temp-lol, 0)+1); } else if(po==temp) { ho.remove(lol,temp); ho.put(lol,temp-1); if(!hola.remove(temp-lol+1,1)) hola.put(temp-lol+1, hola.get(temp-lol+1)-1); hola.put(temp-lol, hola.getOrDefault(temp-lol, 0)+1); } else { ho.remove(lol); if(!hola.remove(temp-lol+1,1)) hola.put(temp-lol+1, hola.get(temp-lol+1)-1); ho.put(lol, po-1); ho.put(po+1,temp); hola.put(po-lol, hola.getOrDefault(po-lol, 0)+1); hola.put(temp-po, hola.getOrDefault(temp-po, 0)+1); } if(hola.size()==1) { if(ho.size()>=ans) { ans=ho.size(); val=a[pos[i]]+1; } } } pr(val); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static class pair { int a,b; pair() { }; pair(int c,int d) { a=c; b=d; } } void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class iter { vecti a; int curi=0; iter(vecti b) { a=b; } public boolean hasNext() { if(a.size<curi) return true; return false; } public int next() { return a.a[curi++]; } public int prev() { return a.a[--curi]; } } static class vecti { int a[],size; vecti() { a=new int[10]; size=0; } vecti(int n) { a=new int[n]; size=0; } public void add(int b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public iter iterator() { return new iter(this); } } static class lter { vectl a; int curi=0; lter(vectl b) { a=b; } public boolean hasNext() { if(a.size<curi) return true; return false; } public long next() { return a.a[curi++]; } public long prev() { return a.a[--curi]; } } static class vectl { long a[]; int size; vectl() { a=new long[10]; size=0; } vectl(int n) { a=new long[n]; size=0; } public void add(long b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public lter iterator() { return new lter(this); } } static class dter { vectd a; int curi=0; dter(vectd b) { a=b; } public boolean hasNext() { if(a.size<curi) return true; return false; } public double next() { return a.a[curi++]; } public double prev() { return a.a[--curi]; } } static class vectd { double a[]; int size; vectd() { a=new double[10]; size=0; } vectd(int n) { a=new double[n]; size=0; } public void add(double b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public dter iterator() { return new dter(this); } } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return in.nextInt();} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} static vecti niv(int n) {vecti a=new vecti(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=ni();return a;} static vectl nlv(int n) {vectl a=new vectl(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nl();return a;} static vectd ndv(int n) {vectd a=new vectd(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.exit(0);} static void psort(int[][] a) { Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; else if(b[0]>a[0]) return -1; return 0; } }); } static String pr(String a, long b) { String c=""; while(b>0) { if(b%2==1) c=c.concat(a); a=a.concat(a); b>>=1; } return c; } static long powm(long a, long b, long m) { long an=1; long c=a; while(b>0) { if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static int gcd(int a, int b) { if(b==0) return a; else return gcd(b, a%b); } static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
518dff2dab7e110bc74222f7d5adae62
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.util.*; import java.io.*; // Solution public class Main { public static void main (String[] argv) { new Main(); } class Item implements Comparable<Item>{ int val, pos; public Item(int v, int p) { this.val = v; this.pos = p; } public int compareTo(Item o) { return o.val - val; } } boolean test = false; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); int n = in.nextInt(); Item[] a = new Item[n]; for (int i = 0; i < n; i++) { int v = in.nextInt(); a[i] = new Item(v, i); } Arrays.sort(a); if(test){ for (Item i : a) System.out.println(i.pos + " " + i.val); } if (n == 1) { System.out.println((a[0].val + 1)); return; } int maxSeg = 1; int bestk = a[0].val + 1; HashMap<Integer, Integer> map = new HashMap<>(); TreeSet<Integer> set = new TreeSet<>(); int k = a[0].val, p = a[0].pos; set.add(p); if (p == 0 || p == n - 1) { map.put(n - 1, 1); if(test)System.out.println("put " + (n-1) + " : " + 1); bestk = k; }else { int l = p, r = n - 1 - p; if (l == r) { map.put(l, 2); bestk = k; maxSeg = 2; if(test)System.out.println("put " + l + " : " + 2); }else { map.put(l, 1); map.put(r, 1); if(test)System.out.println("put " + l + " : " + 1); if(test)System.out.println("put " + r + " : " + 1); } } int slen = -1; for (int i = 1; i < n - 1; i++) { k = a[i+1].val +1; p = a[i].pos; //use this k Integer higher = set.higher(p); Integer lower = set.lower(p); if (higher == null) { int len = n - lower - 1; int cnt = map.get(len); if (cnt == 1) { map.remove(len); if(test)System.out.println("remove " + len); } else { map.put(len, cnt - 1); if(test)System.out.println("put " + len + " : " + (cnt - 1)); } if (p == lower + 1 || p == n - 1) { len--; if (len != 0) { cnt = 1; if (map.containsKey(len)) cnt += map.get(len); map.put(len, cnt); if(test)System.out.println("put " + len + " : " + cnt); } }else { int l = p - lower - 1; int r = n - p - 1; slen = r; if (l == r) { cnt = 2; if (map.containsKey(l)) cnt += map.get(l); map.put(l,cnt); if(test)System.out.println("put " + l + " : " + cnt); }else { cnt = 1; if (map.containsKey(l)) cnt += map.get(l); map.put(l,cnt); if(test)System.out.println("put " + l + " : " + cnt); cnt = 1; if (map.containsKey(r)) cnt += map.get(r); map.put(r,cnt); if(test)System.out.println("put " + r + " : " + cnt); } } }else if (lower == null) { int len = higher; int cnt = map.get(len); if (cnt == 1) { map.remove(len); if(test)System.out.println("remove " + len); } else { map.put(len, cnt - 1); if(test)System.out.println("put " + len + " : " + (cnt - 1)); } if (p == higher - 1 || p == 0) { len--; if (len != 0) { cnt = 1; if (map.containsKey(len)) cnt += map.get(len); map.put(len, cnt); if(test)System.out.println("put " + len + " : " + cnt); } }else { int l = higher - p - 1; int r = p; if (l == r) { cnt = 2; if (map.containsKey(l)) cnt += map.get(l); map.put(l,cnt); if(test)System.out.println("put " + l + " : " + cnt); }else { cnt = 1; if (map.containsKey(l)) cnt += map.get(l); map.put(l,cnt); if(test)System.out.println("put " + l + " : " + cnt); cnt = 1; if (map.containsKey(r)) cnt += map.get(r); map.put(r,cnt); if(test)System.out.println("put " + r + " : " + cnt); } } }else { //both not null int len = higher - lower - 1; int cnt = map.get(len); if (cnt == 1) { map.remove(len); if(test)System.out.println("remove " + len); } else { map.put(len, cnt - 1); if(test)System.out.println("put " + len + " : " + (cnt - 1)); } int l = p - lower - 1; int r = higher - p - 1; slen = r; if (l == r) { if (l != 0) { cnt = 2; if (map.containsKey(l)) cnt += map.get(l); map.put(l,cnt); if(test)System.out.println("put " + l + " : " + cnt); } }else { if (l != 0) { cnt = 1; slen = l; if (map.containsKey(l)) cnt += map.get(l); if(test)System.out.println("put " + l + " : " + cnt); map.put(l,cnt); } if (r != 0) { cnt = 1; if (map.containsKey(r)) cnt += map.get(r); if(test)System.out.println("put " + r + " : " + cnt); map.put(r,cnt); } } } //check if (map.size() == 1) { //a valid one for (int cur : map.values()) { if (cur >= maxSeg) { maxSeg = cur; bestk = k; } } } set.add(p); } System.out.println(bestk); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return ""; //e.printStackTrace(); } return str; } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
c551fd33163f6edfe886e9bd06d05206
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } static class Solver { private int n; private int[] L; private int[] R; private int[] M; private int FindLeft(int i) { if (L[i] < 0) { return i; } return L[i] = FindLeft(L[i]); } private int FindRight(int i) { if (R[i] < 0) { return i; } return R[i] = FindRight(R[i]); } private class Pair implements Comparable<Pair> { public int x, y; Pair() { } Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair P) { if (x != P.x) { return x - P.x; } return y - P.y; } } private void Mod(TreeMap<Integer, Integer> T, int k, int d) { if (T.get(k) == null && d == -1) { return; } int x = T.get(k) == null ? 0 : T.get(k); if (x + d > 0) { T.put(k, x + d); } else { T.remove(k); } } private void solve(InputReader inp, PrintWriter out) { n = inp.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = inp.nextInt(); } Pair[] b = new Pair[n]; for (int i = 0; i < n; ++i) { b[i] = new Pair(a[i], i); } Arrays.sort(b); Pair ans = new Pair(-1, (int) 1e9 + 1); L = new int[n]; R = new int[n]; M = new int[n]; TreeMap<Integer, Integer> S = new TreeMap<>(); for (int i = 0; i < n; ++i) { L[i] = -1; R[i] = -1; M[i] = 0; } for (int i = 0; i < n; ++i) { int j = i; while (j < n - 1 && b[j + 1].x == b[i].x) { j += 1; } for (int k = i; k <= j; ++k) { int p = b[k].y; M[p] = 1; if (p > 0 && M[p - 1] == 1) { L[p] = p - 1; R[p - 1] = p; } if (p < n - 1 && M[p + 1] == 1) { R[p] = p + 1; L[p + 1] = p; } int l = FindLeft(p); int r = FindRight(p); Mod(S, p - l, -1); Mod(S, r - p, -1); Mod(S, r - l + 1, 1); } if (S.size() > 0 && S.firstKey().equals(S.lastKey())) { Pair t = new Pair(-S.firstEntry().getValue(), b[i].x + 1); if (ans.compareTo(t) > 0) { ans = t; } } i = j; } out.println(ans.y); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
7b81c5a502cb98d8eb64619a6aa190de
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; public class Main { static long mod = 1000000007L; static FastScanner scanner; static int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67}; static List<Integer>[] w;// = new List[500000]; static long[] visited = new long[500000]; static boolean[] vis2 = new boolean[500000]; public static void main(String[] args) { scanner = new FastScanner(); int n = scanner.nextInt(); int[] a = scanner.nextIntArray(n); Unit[] units = new Unit[n]; for (int i = 0; i < n; i++) units[i] = new Unit(a[i], i); Arrays.sort(units); Map<Integer, Segment> byStart = new HashMap<>(); Map<Integer, Segment> byEnd = new HashMap<>(); TreeSet<Segment> allSegments = new TreeSet<>(); int currentMax = 0; int response = 0; for (Unit u : units) { Segment previous = byEnd.get(u.index - 1); Segment next = byStart.get(u.index + 1); if (previous != null) { byStart.remove(previous.s); byEnd.remove(previous.e); allSegments.remove(previous); } if (next != null) { byEnd.remove(next.e); byStart.remove(next.s); allSegments.remove(next); } Segment segmentToConsider; if (previous == null && next == null) { segmentToConsider = new Segment(u.index, u.index); } else if (previous != null && next != null) { segmentToConsider = new Segment(previous.s, next.e); } else if (previous != null) { segmentToConsider = new Segment(previous.s, u.index); } else { segmentToConsider = new Segment(u.index, next.e); } byStart.put(segmentToConsider.s, segmentToConsider); byEnd.put(segmentToConsider.e, segmentToConsider); allSegments.add(segmentToConsider); if (allSegments.first().length() == allSegments.last().length()) { if (allSegments.size() > currentMax) { currentMax = allSegments.size(); response = u.value + 1; } } } System.out.println(response); } static class Segment implements Comparable<Segment> { int s, e; public Segment(int s, int e) { this.s = s; this.e = e; } public int length() { return e - s + 1; } @Override public int compareTo(Segment o) { if (length() == o.length()) { return s - o.s; } return length() - o.length(); } } static class Unit implements Comparable<Unit> { int value; int index; public Unit(int value, int index) { this.value = value; this.index = index; } @Override public int compareTo(Unit o) { return this.value - o.value; } } public static class FastScanner { BufferedReader br; StringTokenizer st; 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(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i ++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } } //4 - 1 * 6 * 2 = 12 //5 - 4 * 6 * 2 = 48 //5(2) - 4 * 1 * 6 * 1 = 24 //3 - 2 * 2 = 4 //4(1) - 3 * 2 * 2 = 12 //4(2) - 3 * 2 = 6 //-------------------- // 7 3 // 4 - 1 * 6 * 6 = 36 C(3,3) // 5 - 1 * c(4,3) // c(5,3) // 1 // 1 // 8 10 16 // 8 1 //1 17 1 0 0 0 0 0 0 21 0 0 0 0
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
5e10546412ace3950e3828d7cbf3f529
train_001.jsonl
1526574900
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For $$$n$$$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $$$k$$$ that if the shark in some day traveled the distance strictly less than $$$k$$$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $$$k$$$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $$$k$$$.The shark never returned to the same location after it has moved from it. Thus, in the sequence of $$$n$$$ days we can find consecutive nonempty segments when the shark traveled the distance less than $$$k$$$ in each of the days: each such segment corresponds to one location. Max wants to choose such $$$k$$$ that the lengths of all such segments are equal.Find such integer $$$k$$$, that the number of locations is as large as possible. If there are several such $$$k$$$, print the smallest one.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { class pair{ int v,id;pair(int a,int b){v=a;id=b;} } class bound{ int l,r;bound(int a,int b){l=a;r=b;} } void upd(int v,boolean t){ if(t){ if(sz[v]==0)++cnt; sz[v]++; }else{ if(sz[v]==1)--cnt; sz[v]--; } } int sz[]=new int[100010],cnt=0,max=-1; public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(),ans=0; int a[]=new int[n]; ArrayList<Integer> al1=new ArrayList<>();ArrayList<pair> al2=new ArrayList<>(); for(int i=0;i<n;i++){ a[i]=in.nextInt();al1.add(a[i]);al1.add(a[i]+1);al2.add(new pair(a[i],i)); } Collections.sort(al1); Collections.sort(al2,new Comparator<pair>(){ public int compare(pair p1,pair p2){ return p1.v-p2.v; } }); int p=0; TreeSet<bound> bound=new TreeSet<>(new Comparator<bound>(){ public int compare(bound b1,bound b2){ return b1.l-b2.l; } }); int aid=0; for(int i=0;i<2*n;i++){ int v=al1.get(i),j; for(j=p;j<n;j++){ pair p1=al2.get(j); if(p1.v>=v){ p=j;break; } bound b1=bound.floor(new bound(p1.id,0)); bound b2=bound.ceiling(new bound(p1.id,0)); if(b1==null){ if(b2==null){ bound.add(new bound(p1.id,p1.id)); upd(1,true); if(cnt==1)max=sz[1]; }else{ if(b2.l==p1.id+1){ bound.remove(b2); bound.add(new bound(p1.id,b2.r)); upd(b2.r-p1.id+1,true); upd(b2.r-b2.l+1,false); if(cnt==1)max=sz[b2.r-p1.id+1]; }else{ bound.add(new bound(p1.id,p1.id)); upd(1,true); if(cnt==1)max=sz[1]; } } }else{ if(b2==null){ if(b1.r==p1.id-1){ bound.remove(b1); bound.add(new bound(b1.l,p1.id)); upd(b1.r-b1.l+1,false); upd(p1.id-b1.l+1,true); if(cnt==1)max=sz[p1.id-b1.l+1]; }else{ bound.add(new bound(p1.id,p1.id)); upd(1,true); if(cnt==1)max=sz[1]; } }else{ if(b1.r==p1.id-1){ if(b2.l==p1.id+1){ bound.remove(b1); bound.remove(b2); bound.add(new bound(b1.l,b2.r)); upd(b1.r-b1.l+1,false); upd(b2.r-b2.l+1,false); upd(b2.r-b1.l+1,true); if(cnt==1)max=sz[b2.r-b1.l+1]; }else{ bound.remove(b1); bound.add(new bound(b1.l,p1.id)); upd(b1.r-b1.l+1,false); upd(p1.id-b1.l+1,true); if(cnt==1)max=sz[p1.id-b1.l+1]; } }else{ if(b2.l==p1.id+1){ bound.remove(b2); bound.add(new bound(p1.id,b2.r)); upd(b2.r-p1.id+1,true); upd(b2.r-b2.l+1,false); if(cnt==1)max=sz[b2.r-p1.id+1]; }else{ bound.add(new bound(p1.id,p1.id)); upd(1,true); if(cnt==1)max=sz[1]; } } } } // System.out.println(v+" "+" "+p1.v+" "+max); // for(int z=1;z<5;z++)System.out.print(sz[z]+" "); // System.out.println(); }p=j; if(cnt==1){ if(max>ans){ ans=max;aid=v; } } } out.println(aid); } // int ja[][],from[],to[],c[]; // void make(int n,int m,InputReader in){ // ja=new int[n+1][];from=new int[m];to=new int[m];c=new int[n+1]; // for(int i=0;i<m;i++){ // from[i]=in.nextInt();to[i]=in.nextInt(); // c[from[i]]++;c[to[i]]++; // } // for(int i=1;i<=n;i++){ // ja[i]=new int[c[i]];c[i]=0; // } // for(int i=0;i<m;i++){ // ja[from[i]][c[from[i]]++]=to[i]; // ja[to[i]][c[to[i]]++]=from[i]; // } // } // pair[] radixSort(pair[] f){ return radixSort(f, f.length); } // pair[] radixSort(pair[] f, int n) // { // pair[] to = new pair[n]; // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i].v&0xffff)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++){ // to[b[f[i].v&0xffff]++] = f[i]; // } // pair[] d = f; f = to;to = d; // } // { // int[] b = new int[65537]; // for(int i = 0;i < n;i++)b[1+(f[i].v>>>16)]++; // for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; // for(int i = 0;i < n;i++)to[b[f[i].v>>>16]++] = f[i]; // pair[] d = f; f = to;to = d; // } // return f; // } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["8\n1 2 7 3 4 8 5 6", "6\n25 1 2 3 14 36"]
1 second
["7", "2"]
NoteIn the first example the shark travels inside a location on days $$$1$$$ and $$$2$$$ (first location), then on $$$4$$$-th and $$$5$$$-th days (second location), then on $$$7$$$-th and $$$8$$$-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the $$$2$$$-nd day, so there is only one location.
Java 8
standard input
[ "data structures", "dsu", "trees", "brute force" ]
b3d093272fcb289108fe45be8c72f38e
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of days. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the distance traveled in each of the day.
1,900
Print a single integer $$$k$$$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $$$k$$$ is smallest possible satisfying the first and second conditions.
standard output
PASSED
76e9c4bd248beacaf2cf910b056c1085
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int q = scanner.nextInt(), c, m, x; for (int i = 0; i < q; i++) { c = scanner.nextInt(); m = scanner.nextInt(); x = scanner.nextInt(); System.out.println(getNumPerfectTeams(c, m, x)); } } private static int getNumPerfectTeams(int c, int m, int x) { int result = 0, minValue; if (c == 0 || m == 0 || (c + m + x) < 3) return result; while (c != 0 && m != 0) { if (x != 0) { minValue = Math.min(Math.min(c, m), x); result += minValue; c -= minValue; m -= minValue; x -= minValue; } else { result += getNumOfTriplets(m, c); return result; } } return result; } private static int getNumOfTriplets(int m, int c) { if (m + c < 3) return 0; else return Math.min(Math.min(m, c), (m + c) / 3); } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
0e31c2fc1df1d8ceed375b345564c888
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
//package codeChefSep19; import java.io.*; import java.util.*; public class ICPC { public static void main(String[] args)throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int q=Integer.parseInt(br.readLine()); for(int i=0;i<q;i++) { StringTokenizer st=new StringTokenizer(br.readLine()); int c=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); int any=Integer.parseInt(st.nextToken()); int team=0; if(c<=m) { any=any+m-c; m=c; if(any<c) { int diff=c-any; int qt=(int)Math.ceil((double)diff/3); c=c-qt; } System.out.println(Math.min(c, m)); } else if(m<=c) { any=any+c-m; c=m; if(any<m) { int diff=c-any; int qt=(int)Math.ceil((double)diff/3); c=c-qt; } System.out.println(Math.min(c,m)); } } } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
510f5b8397656c136e9ef446528b149e
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import java.util.Scanner; public class C1221 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); while(q-- > 0) { int c = scan.nextInt(); int m = scan.nextInt(); int x = scan.nextInt(); int noOfTeams = 0; int min = Math.min(c,m); if(min>x) { noOfTeams = x; c -= x; m -= x; } else { c -= min; m -= min; noOfTeams = min; } int low = 0; min = Math.min(c,m); int compareMin = min; while(low<=min) { int mid = (min - low)/2 + low; int test = c+m-mid*3; if(test < 3 && test >= 0) { noOfTeams += mid; break; } else if(mid == compareMin) { noOfTeams += mid; break; } else if(test < 0) { min = mid -1; } else if(test >=3) { low = mid +1; } } System.out.println(noOfTeams); } } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
c5bf0499dba1be98546e914629a99893
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import java.util.Scanner; public class C1221 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); while(q-- > 0) { int c = scan.nextInt(); int m = scan.nextInt(); int x = scan.nextInt(); System.out.println(Math.min(Math.min(c, m), (c+m+x)/3)); } } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
43616f8415a0628e5f3d6c91b78c2b29
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; /*CODE BY SHIKHAR TYAGI*/ public class C { public static void main(String args[]) { FastScanner scn = new FastScanner(); int q = scn.nextInt(); while (q-- > 0) { int c = scn.nextInt(); int m = scn.nextInt(); int x = scn.nextInt(); if (Math.min(c, m) <= x) { System.out.println(Math.min(c, m)); } else { c -= x; m -= x; System.out.println(x + Math.min(Math.min(c, m), (c + m) / 3)); } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } } class str { String str; int count; char lasVowel; str(String str, int count, char lasVowel) { this.str = str; this.count = count; this.lasVowel = lasVowel; } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
ab2d8a9f066af0da2a4d3140bd0321f1
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import org.omg.CORBA.INTERNAL; import org.omg.CORBA.MARSHAL; import javax.swing.plaf.basic.BasicTreeUI; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { private static Scanner sc; private static Printer pr; static boolean []visited; static int []color; static int []pow=new int[(int)3e5+1]; static int []count; static boolean check=true; static boolean checkBip=true; static TreeSet<Integer>[]list; private static long aLong=(long)(Math.pow(10,9)+7); static final long div=998244353; static int answer=0; static int[]countSubTree; static int[]colorNode; static boolean con=true; static ArrayList<Integer>dfsPath=new ArrayList<>(); static ArrayList<Integer>ans=new ArrayList<>(); static boolean[]rec; static int min=Integer.MAX_VALUE; static ArrayList<Task>tasks=new ArrayList<>(); static boolean []checkpath; static long []out; private static void solve() throws IOException { int q=sc.nextInt(); while (q-->0){ long coder=sc.nextLong(),math=sc.nextLong(),x=sc.nextLong(); long sum=coder+math+x; sum/=3; if (sum<=coder&&sum<=math)pr.println(sum); else pr.println(Math.min(Math.min(coder,math),sum)); } } public static class pp { long head,tail,wheight; public pp(long h,long t,long w) { this.head = h; this.tail = t; this.wheight=w; } } public static class dsu{ int []rank; int[]parent; long []sum; int n; public dsu(int n) { this.n = n; parent=new int[n]; rank=new int[n]; sum=new long[n]; for (int i=0;i<n;++i){ rank[i]=1; parent[i]=i; sum[i]=0; } } public int dad(int child){ if (parent[child]==child)return child; else return dad(parent[child]); } public void merge(int u,int v){ int dadU=dad(u); int dadV=dad(v); if (dadU==dadV)return ; if (u!=v){ if (rank[u]<rank[v]){ parent[u]=v; rank[v]+=rank[u]; } else if (rank[u]==rank[v]){ parent[u]=v; rank[v]+=rank[u]; } else{ parent[v]=u; rank[u]+=rank[v]; } } } } public static long power(long x,long y,long mods){ if (y==0) return 1%mods; long u=power(x,y/2,mods); u=((u)*(u))%mods; if (y%2==1) u=(u*(x%mods))%mods; return u; } public static class Task implements Comparable<Task>{ long l,r; public Task(long w,long v) { this.l=w; this.r=v; } @Override public int compareTo(Task o) { if (o.l<this.l)return 1; else if (o.l>this.l)return -1; else { if (o.r>this.r)return 1; else if (o.r<this.r)return -1; } return 0; } } public static void printSolve(StringBuilder str, int[] colors, int n,int color){ for(int i = 1;i<=n;++i) if(colors[i] == color) str.append(i + " "); str.append('\n'); } public static class pairTask{ int val; int size; public pairTask(int x, int y) { this.val = x; this.size = y; } } public static void subTree(int src,int parent,int x){ countSubTree[src]=1; if (src==x) { checkpath[src]=true; //System.out.println("src:"+src); } else checkpath[src]=false; for (int v:list[src]){ if (v==parent) continue; subTree(v,src,x); countSubTree[src]+=countSubTree[v]; checkpath[src]|=checkpath[v]; } } public static boolean prime(long src){ for (int i=2;i*i<=src;i++){ if (src%i==0) return false; } return true; } public static void bfsColor(int src){ Queue<Integer>queue = new ArrayDeque<>(); queue.add(src); while (!queue.isEmpty()){ boolean b=false; int vertex=-1,p=-1; int poll=queue.remove(); for (int v:list[poll]){ if (color [v]==0){ vertex=v; break; } } for (int v:list[poll]){ if (color [v]!=0&&v!=vertex){ p=v; break; } } for (int v:list[p]){ if (color [v]!=0){ color[vertex]=color[v]; b=true; break; } } if (!b){ color[vertex]=color[poll]+1; } } } static int add(int a,int b ){ if (a+b>=div) return (int)(a+b-div); return (int)a+b; } public static int isBipartite(ArrayList<Integer>[]list,int src){ color[src]=0; Queue<Integer>queue=new LinkedList<>(); int []ans={0,0}; queue.add(src); while (!queue.isEmpty()){ ans[color[src=queue.poll()]]++; for (int v:list[src]){ if (color[v]==-1){ queue.add(v); color[v]=color[src]^1; }else if (color[v]==color[src]) check=false; } } return add(pow[ans[0]],pow[ans[1]]); } public static int powerMod(long b, long e){ long ans=1; while (e-->0){ ans=ans*b%div; } return (int)ans; } public static int dfs(int s){ int ans=1; visited[s]=true; for (int k:list[s]){ if (!visited[k]){ ans+=dfs(k); } } return ans; } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; 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 < f.length; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static long []primeFactor(int n){ long []prime=new long[n+1]; prime[1]=1; for (int i=2;i<=n;i++) prime[i]=((i&1)==0)?2:i; for (int i=3;i*i<=n;i++){ if (prime[i]==i){ for (int j=i*i;j<=n;j+=i){ if (prime[j]==j) prime[j]=i; } } } return prime; } public static StringBuilder binaryradix(long number){ StringBuilder builder=new StringBuilder(); long remainder; while (number!=0) { remainder = number % 2; number >>= 1; builder.append(remainder); } builder.reverse(); return builder; } public static int binarySearch(long[] a, int index,long target) { int l = index; int h = a.length - 1; while (l<=h) { int med = l + (h-l)/2; if(a[med] - target <= target) { l = med + 1; } else h = med - 1; } return h; } public static int val(char c){ return c-'0'; } public static long gcd(long a,long b) { if (a == 0) return b; return gcd(b % a, a); } private static class Pair implements Comparable<Pair> { long x; long y; Pair() { this.x = 0; this.y = 0; } Pair(long x, long y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) return false; Pair other = (Pair) obj; if (this.x == other.x && this.y == other.y) { return true; } return false; } @Override public int compareTo(Pair other) { if (this.x != other.x) return Long.compare(this.x, other.x); return Long.compare(this.y*other.x, this.x*other.y); } } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pr = new Printer(System.out); solve(); pr.close(); // sc.close(); } private static class Scanner { BufferedReader br; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } private boolean isPrintable(int ch) { return ch >= '!' && ch <= '~'; } private boolean isCRLF(int ch) { return ch == '\n' || ch == '\r' || ch == -1; } private int nextPrintable() { try { int ch; while (!isPrintable(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } return ch; } catch (IOException e) { throw new NoSuchElementException(); } } String next() { try { int ch = nextPrintable(); StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (isPrintable(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } int nextInt() { try { // parseInt from Integer.parseInt() boolean negative = false; int res = 0; int limit = -Integer.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } int multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } long nextLong() { try { // parseLong from Long.parseLong() boolean negative = false; long res = 0; long limit = -Long.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Long.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } long multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { int ch; while (isCRLF(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (!isCRLF(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } void close() { try { br.close(); } catch (IOException e) { // throw new NoSuchElementException(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class List { String Word; int length; List(String Word, int length) { this.Word = Word; this.length = length; } } private static class Printer extends PrintWriter { Printer(PrintStream out) { super(out); } } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
1c24a10f55af62494b06a5f12b808a5e
train_001.jsonl
1568903700
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; import java.util.HashSet; 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); Task solver = new Task(); int q; q=in.nextInt(); for(int i=0;i<q;i++) solver.solve(1, in, out); out.close(); } static class Task { public int solve(int testNumber, InputReader in, PrintWriter out) { int ans,c,m,x,p,q,tmp,ex; c=in.nextInt(); m=in.nextInt(); x=in.nextInt(); p=Math.max(c,m); q=Math.min(c,m); ans=0; if(q > x){ p=p-x; q=q-x; ans=x; if(p>=2*q ){ ans+=q; } else{ tmp=p-q; ans=ans+tmp; p=p-2*tmp; q-=tmp; tmp=p/3; ans=ans+tmp*2; if(p-3*tmp > 1) ans++; } } else{ ans=q; } out.println(ans); return 0; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1"]
2 seconds
["1\n3\n0\n0\n1\n3"]
NoteIn the first example here are how teams are formed: the only team of 1 coder, 1 mathematician and 1 without specialization; all three teams consist of 1 coder and 2 mathematicians; no teams can be formed; no teams can be formed; one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team; one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.
Java 8
standard input
[ "binary search", "math" ]
b18dac401b655c06bee331e71eb3e4de
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.
1,200
Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
standard output
PASSED
337e01199bbf43f414e8ca8f9465b983
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.*; import java.io.*; public class A { public static boolean isPosInt(StringBuilder str, int s, int e) { if (e - s < 1 || (str.charAt(s) == '0' && e - s > 1)) return false; for (int i = s; i < e; i++) if (!isDigit(str, i)) return false; return true; } public static boolean isDigit(StringBuilder str, int i) { return (str.charAt(i) - '0' >= 0 && str.charAt(i) - '0' <= 9); } public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuilder str = new StringBuilder(in.nextLine()); StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); ArrayList<Integer> wbreaks = new ArrayList<Integer>(); wbreaks.add(-1); for (int i = 0; i < str.length(); i++) if (str.charAt(i) == ';' || str.charAt(i) == ',') wbreaks.add(i); wbreaks.add(str.length()); int s, e; for (int i = 0; i < wbreaks.size() - 1; i++) { s = wbreaks.get(i) + 1; e = wbreaks.get(i + 1); if (A.isPosInt(str, s, e)) { a.append(str.subSequence(s, e)); a.append(','); } else { b.append(str.subSequence(s, e)); b.append(','); } } if (a.length() == 0) System.out.println("-"); else { a.deleteCharAt(a.length() - 1); System.out.println("\"" + a.toString() + "\""); } if (b.length() == 0) System.out.println("-"); else { b.deleteCharAt(b.length() - 1); System.out.println("\"" + b.toString() + "\""); } } } class QuickScanner { BufferedReader in; StringTokenizer token; String delim; public QuickScanner(InputStream inputStream) { this.in=new BufferedReader(new InputStreamReader(inputStream)); this.delim=" \n\t"; this.token=new StringTokenizer("",delim); } public boolean hasNext() { while(!token.hasMoreTokens()) { try { String s=in.readLine(); if(s==null) return false; token=new StringTokenizer(s,delim); } catch (IOException e) { throw new InputMismatchException(); } } return true; } public String next() { hasNext(); return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
cd0da545737374271c6763c69876fb5f
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.ArrayList; 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 * @author Andrew Govorovsky ( AndrewG ) */ 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); Task600A solver = new Task600A(); solver.solve(1, in, out); out.close(); } } class Task600A { public void solve(int testNumber, InputReader in, PrintWriter out) { String src = in.readLine(); ArrayList<String> a = new ArrayList<>(); ArrayList<String> b = new ArrayList<>(); int prevDelimiter = 0; for (int i = 0; i < src.length(); i++) { if (src.charAt(i) == ',' || src.charAt(i) == ';') { String toAnalyze = src.substring(prevDelimiter, i); analyze(toAnalyze, a, b); prevDelimiter = i + 1; } } analyze(src.substring(prevDelimiter, src.length()), a,b); if (a.size() == 0) { out.print("-"); } else { out.print("\""); for (int i = 0; i < a.size(); i++) { out.print(a.get(i) ); if (i + 1 != a.size()) { out.print(","); } } out.print("\""); } out.println(); if (b.size() == 0) { out.print("-"); } else { out.print("\""); for (int i = 0; i < b.size(); i++) { out.print(b.get(i)); if (i + 1 != b.size()) { out.print(","); } } out.print("\""); } } private void analyze(String string, ArrayList<String> a, ArrayList<String> b) { if (string.length() == 0) { b.add(""); return; } if (string.charAt(0) == '0') { if (string.length() == 1) { a.add("0"); } else { b.add(string); } return; } for (int i = 0; i < string.length(); i++) { if (!Character.isDigit(string.charAt(i))) { b.add(string); return; } } a.add(string); } } class InputReader { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; private static final String dlms = " \n\r\f\t"; public InputReader(InputStream inputStream) { this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); this.stringTokenizer = new StringTokenizer("", dlms); } public String readLine() { try { return bufferedReader.readLine(); } catch (IOException e) { /* ignore */ } return null; } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
dbc4e2230ad7e53b1ad6102d4119d9a0
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\\\d+)?"); //match a number with optional '-' and decimal. } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s=sc.next(); int j=0; ArrayList<String > rs=new ArrayList<String>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)==';'){ rs.add(s.substring(j,i)); j=i+1; } if(s.charAt(i)==','){ rs.add(s.substring(j,i)); j=i+1; } } ArrayList<String> val=new ArrayList<String>(); ArrayList<String> val2=new ArrayList<String>(); rs.add(s.substring(j,s.length())); for(int i=0;i<rs.size();i++) { if(isNumeric(rs.get(i))){ if(rs.get(i).charAt(0)=='0' && rs.get(i).length()>1) val2.add(rs.get(i)); else val.add(rs.get(i)); }else { val2.add(rs.get(i)); } } if(val.size()==0) System.out.println("-"); else{ System.out.print("\""); for(int i=0;i<val.size()-1;i++) System.out.print(val.get(i)+","); System.out.println(val.get(val.size()-1)+"\""); } if(val2.size()==0) System.out.println("-"); else{ System.out.print("\""); for(int i=0;i<val2.size()-1;i++) System.out.print(val2.get(i)+","); System.out.println(val2.get(val2.size()-1)+"\""); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
25bbc179c1e56ade054e3fe93826790e
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class ECR2A { public static void main(String[] args) { FastScanner in=new FastScanner(); char[] s=in.nextToken().toCharArray(); int n=s.length; for(int i=0;i<n;i++) if(s[i]==';') s[i]=','; String[] S=(String.valueOf(s)+" ").split(","); S[S.length-1]=S[S.length-1].trim(); int m=S.length; ArrayList<String> a=new ArrayList<String>(); ArrayList<String> b=new ArrayList<String>(); for(int i=0;i<m;i++){ if(S[i].length()==0){ b.add(""); }else if(S[i].charAt(0)=='0'&&S[i].length()>1){ b.add(S[i]); }else{ boolean f=false; for(int j=0;j<S[i].length()&&!f;j++){ if(S[i].charAt(j)<'0'||S[i].charAt(j)>'9'){ f=true; } } if(!f) a.add(S[i]); else b.add(S[i]); } } PrintWriter out=new PrintWriter(System.out); if(a.size()==0){ out.println("-"); }else{ out.print("\""); for(int i=0;i<a.size();i++){ if(i==0) out.print(a.get(i)); else out.print(","+a.get(i)); } out.println("\""); } if(b.size()==0){ out.println("-"); }else{ out.print("\""); for(int i=0;i<b.size();i++){ if(i==0) out.print(b.get(i)); else out.print(","+b.get(i)); } out.println("\""); } out.flush(); out.close(); } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));} String nextToken(){ while(st==null||!st.hasMoreElements()) try{st=new StringTokenizer(br.readLine());}catch(Exception e){} return st.nextToken(); } int nextInt(){return Integer.parseInt(nextToken());} long nextLong(){return Long.parseLong(nextToken());} double nextDouble(){return Double.parseDouble(nextToken());} } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
724bb534a2d7b1e6a2641f6dae6da03f
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class A { public boolean isDelimita(char ch) { if(ch == ',' || ch == ';')return true; return false; } public boolean isDigit(String s) { if(s.length() == 0)return false; if(s.length() != 1 && s.charAt(0) == '0')return false; for(int i = 0;i < s.length();i++) { if(s.charAt(i) >= '0' &&s.charAt(i) <= '9')continue; return false; } return true; } public void solve() { Scanner cin = new Scanner(System.in); String S = cin.next(); StringBuilder sb = new StringBuilder(); for(int i = 0;i < S.length();i++) { char c = S.charAt(i); if(isDelimita(c) && i + 1 < S.length() && isDelimita(S.charAt(i + 1))) { sb.append(c); sb.append("_"); }else if(isDelimita(c) && i == S.length() - 1) { sb.append(c); sb.append("_"); }else { sb.append(c); } } String[] ss = sb.toString().replace(";",",").split(","); StringBuilder strstr = new StringBuilder(); StringBuilder intint = new StringBuilder(); for(int i = 0;i < ss.length;i++) { if(isDigit(ss[i])) { intint.append(ss[i]); intint.append(","); }else { strstr.append(ss[i]); strstr.append(","); } } String first = intint.length() > 0 ?intint.toString().substring(0,intint.length() - 1) : "-"; String second = strstr.length() > 0?strstr.toString().replace("_","").replace("?",","):"-"; if(!second.equals("-"))second = second.substring(0,second.length() - 1); System.out.println(!first.equals("-")?"\""+first+"\"":first); System.out.println(!second.equals("-")?"\""+second + "\"":second); } public static void main(String[] args) { new A().solve(); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
24947040a5fde646828c89d33a474df3
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); char[] s = (rs()+";").toCharArray(); String tok = null; boolean isInteger = true; boolean startsWithZero = false; boolean isStart = true; StringBuffer a = new StringBuffer(); StringBuffer b = new StringBuffer(); StringBuffer buf = new StringBuffer(); char c; for (int i=0;i<s.length;i++) { c = s[i]; if (c==',' || c==';') { if (buf.length()==0) b.append(","); else { buf.append(","); if (isInteger && (!startsWithZero || buf.length()==2)) { a.append(buf); } else { b.append(buf); } isStart = true; isInteger = true; startsWithZero = false; buf = new StringBuffer(); } } else { if (isStart && c=='0') startsWithZero = true; if (c<'0' || c>'9') isInteger = false; buf.append(c); isStart = false; } } if (a.length()==0) a.append("-"); else a.deleteCharAt(a.length()-1); if (b.length()==0) b.append("-"); else b.deleteCharAt(b.length()-1); String sa = a.toString(), sb = b.toString(); if (!sa.equals("-")) sa = "\""+sa+"\""; if (!sb.equals("-")) sb = "\""+sb+"\""; out.println(sa); out.println(sb); in.close(); out.close(); } public static int ri() throws IOException { return Integer.parseInt(in.readLine()); } public static long rl() throws IOException { return Long.parseLong(in.readLine()); } public static String rs() throws IOException { return in.readLine(); } public static String[] rst() throws IOException { return in.readLine().split(" "); } public static int[] rit() throws IOException { String[] tok = in.readLine().split(" "); int[] res = new int[tok.length]; for (int i = 0; i < tok.length; i++) { res[i] = Integer.parseInt(tok[i]); } return res; } public static long[] rlt() throws IOException { String[] tok = in.readLine().split(" "); long[] res = new long[tok.length]; for (int i = 0; i < tok.length; i++) { res[i] = Long.parseLong(tok[i]); } return res; } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
5173bf6883d15a3cf981a0b40f9d5b2a
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class ExtractNumbers { public static void main(String args[]){ Scanner scan=new Scanner(System.in); String s=scan.next(); StringBuilder num=new StringBuilder(""),other=new StringBuilder(""); String[] next= s.split("[,;]",-1); for(int i=0;i<next.length;i++){ if(isInteger(next[i])){ num.append(next[i]); num.append(","); } else{ other.append(next[i]); other.append(","); } } if(num.length()!=0) System.out.println("\""+num.substring(0,num.length()-1)+"\""); else System.out.println("-"); if(other.length()!=0) System.out.println("\""+other.substring(0,other.length()-1)+"\""); else System.out.println("-"); } public static boolean isInteger( String input ) { if((input.startsWith("0")&&input.length()>1)||input.equals("")) return false; try { BigInteger b=new BigInteger( input ); return true; } catch( Exception e ) { return false; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
4ad6e05085aa49e8f8141b9d287dda20
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by peacefrog on 12/10/15. * Time : 3:56 AM */ public class CF600A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; PrintWriter out; long timeBegin, timeEnd; public void runIO() throws IOException { timeBegin = System.currentTimeMillis(); InputStream inputStream; OutputStream outputStream; if (ONLINE_JUDGE) { inputStream = System.in; Reader.init(inputStream); outputStream = System.out; out = new PrintWriter(outputStream); } else { inputStream = new FileInputStream("/home/peacefrog/Dropbox/IdeaProjects/Problem Solving/input"); Reader.init(inputStream); out = new PrintWriter(System.out); } solve(); out.flush(); out.close(); timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } /* * Start Solution Here */ boolean isNumber(String value) { if(value == null || value.equals("")) { return false; } if(value.charAt(0) == '0' && value.length() != 1) { return false; } if(value.charAt(0) == '-') { return false; } for (int i = 0; i < value.length(); i++) { if(value.charAt(i) < '0' || value.charAt(i) > '9') { return false; } } return true; } private void solve() throws IOException { // int n = Reader.nextInt(); //This Variable default in Code Template String s = Reader.next(); ArrayList<String> firstLine = new ArrayList<>(); ArrayList<String> secondLine = new ArrayList<>(); int a = 0; for (int i = 0; i <= s.length(); i++) { if( i==s.length() || s.charAt(i)== ';' || s.charAt(i)==',' ) { String sub = (s.substring(a , i)); a= i+1; if(isNumber(sub)) firstLine.add(sub); else secondLine.add(sub); } } if(firstLine.isEmpty()) out.println("-"); else { out.print("\""); for (int i = 0; i < firstLine.size(); i++) { if (i==0)out.print(firstLine.get(i)); else out.print(","+firstLine.get(i)); } out.println("\""); } if(secondLine.isEmpty()) out.println("-"); else { out.print("\""); for (int i = 0; i < secondLine.size(); i++) { if (i==0)out.print(secondLine.get(i)); else out.print(","+secondLine.get(i)); } out.println("\""); } } public static void main(String[] args) throws IOException { new CF600A().runIO(); } static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } static String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } static int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
802fa2f0c78d51a75dac5ad1b6c76de0
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class intro{ public static void main(String[] args) throws IOException{ BufferedReader vod=new BufferedReader(new InputStreamReader(System.in)); String str=vod.readLine(); StringBuilder a=new StringBuilder(); StringBuilder b=new StringBuilder(); StringBuilder c=new StringBuilder(); a.append('"'); b.append('"'); for (int i=0; i<str.length(); i++){ if (str.charAt(i)==','||str.charAt(i)==';'){ String s=c.toString(); boolean prov=true; for (int j=0; j<s.length(); j++){ if (!Character.isDigit(s.charAt(j))){ prov=false; break; } } if (prov&&s.length()>0&&(s.charAt(0)!='0'||s.length()==1)){ a.append(s+","); } else{ b.append(s+","); } c=new StringBuilder(); } else{ c.append(str.charAt(i)); } } String s=c.toString(); boolean prov=true; for (int j=0; j<s.length(); j++){ if (!Character.isDigit(s.charAt(j))){ prov=false; break; } } if (prov&&s.length()>0&&(s.charAt(0)!='0'||s.length()==1)){ a.append(s+'"'); b.deleteCharAt(b.length()-1); b.append('"'); } else{ b.append(s+'"'); a.deleteCharAt(a.length()-1); a.append('"'); } if (a.length()>1){ System.out.println(a.toString()); } else{ System.out.println("-"); } if (b.length()>1){ System.out.println(b.toString()); } else{ System.out.println("-"); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
4710474a5f8c68fe5a44c075e10c8429
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.*; import java.util.*; /** * Created by pkumar on 11/27/2015. */ public class ExactNumbers { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); private static int pos; public static void main(String[] args) throws IOException { final String input = readLine(); final char[] inputChars = input.toCharArray(); final ArrayList<String> first = new ArrayList<>(), second = new ArrayList<>(); int startIndex = 0; for (int i = 0; i <= inputChars.length; i++) { if(i == inputChars.length || inputChars[i] == ',' || inputChars[i] == ';') { String value = new String(inputChars, startIndex, i - startIndex); if(isNumber(value)) { first.add(value); } else { second.add(value); } startIndex = i+1; } } if(first.isEmpty()) { out.println("-"); } else { out.print('"'); out.print(first.get(0)); for (int i = 1; i < first.size(); i++) { out.print(','); out.print(first.get(i)); } out.println('"'); } if(second.isEmpty()) { out.println("-"); } else { out.print('"'); out.print(second.get(0)); for (int i = 1; i < second.size(); i++) { out.print(','); out.print(second.get(i)); } out.println('"'); } out.flush(); out.close(); } private static boolean isNumber(String value) { if(value == null || value.equals("")) { return false; } if(value.charAt(0) == '0' && value.length() != 1) { return false; } if(value.charAt(0) == '-') { return false; } for (int i = 0; i < value.length(); i++) { if(value.charAt(i) < '0' || value.charAt(i) > '9') { return false; } } return true; } private static String readLine() throws IOException { return br.readLine().trim(); } private static int readLineInt() throws IOException { return Integer.parseInt(readLine()); } private static String readNextString(String input) { int end; String value; if ((end = input.indexOf(' ', pos)) >= 0) { value = input.substring(pos, end); pos = end + 1; } else { value = input.substring(pos); pos = 0; } return value; } private static int readNextInt(String input) { return Integer.parseInt(readNextString(input)); } private static long readNextLong(String input) { return Long.parseLong(readNextString(input)); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
ddb05f82529f3ac4381362d33f3bca79
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner qwe = new Scanner(System.in); char[] str = qwe.next().toCharArray(); StringBuilder part1 = new StringBuilder(""); StringBuilder part2 = new StringBuilder(""); boolean[] isfirst = new boolean[2]; for (int i = 0; i < isfirst.length; i++) { isfirst[i] = true; } StringBuilder cur = new StringBuilder(""); boolean allnums = true; for (int i = 0; i < str.length; i++) { char at = str[i]; if(at == ',' || at == ';'){ if(cur.length() == 0){ allnums = false; } if(cur.toString().equals("0")) allnums= true; if(allnums){ part1.append( isfirst[0] ? cur : ("," + cur) ); isfirst[0] = false; } else{ part2.append( isfirst[1] ? cur : ("," + cur) ); isfirst[1] = false; } allnums= true; cur = new StringBuilder(""); } else{ cur.append(at); if(at-'0' < 0 || at-'0' > 9 || (cur.length() == 1 && at == '0')){ //System.out.println("at: " +at + " " + (at-'0')); allnums =false; } } } if(cur.length() == 0){ allnums = false; } if(cur.toString().equals("0")) allnums= true; if(allnums){ part1.append( isfirst[0] ? cur : ("," + cur) ); isfirst[0] = false; } else{ part2.append( isfirst[1] ? cur : ("," + cur) ); isfirst[1] = false; } System.out.println(isfirst[0] ? "-" : "\"" + part1 + "\""); System.out.println(isfirst[1] ? "-" : "\"" + part2 + "\""); qwe.close(); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
823e9a507a70abe1a249c6f2783744a5
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.*; import java.util.*; public class Solution { static String convertToString(ArrayList<String> words) { if (words.size() == 0) { return "-"; } StringBuilder result = new StringBuilder("\""); for (int i = 0; i < words.size() - 1; ++i) { result.append(words.get(i)); result.append(","); } result.append(words.get(words.size() - 1) + "\""); return result.toString(); } static boolean isIntegerNumber(String word) { if (word.length() == 0) { return false; } if (word.charAt(0) == '0' && word.length() > 1) { return false; } for (int i = 0; i < word.length(); ++i) { if (word.charAt(i) < '0' || word.charAt(i) > '9') { return false; } } return true; } static ArrayList<String> parseWords(String text) { ArrayList<String> words = new ArrayList<String>(); StringBuilder current = new StringBuilder(); for (int i = 0; i < text.length(); ++i) { char c = text.charAt(i); if (c == ',' || c == ';') { words.add(current.toString()); current.setLength(0); } else { current.append(c); } } words.add(current.toString()); return words; } public static void main(String[] args) { MyScanner sc = new MyScanner(); String text = sc.next(); ArrayList<String> words = parseWords(text); ArrayList<String> numbers = new ArrayList<String>(); ArrayList<String> rest = new ArrayList<String>(); for (String word : words) { if (isIntegerNumber(word)) { numbers.add(word); } else { rest.add(word); } } System.out.println(convertToString(numbers)); System.out.println(convertToString(rest)); } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
1445b736ea7f5f8e5d203b7604f2c73a
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class Main{ // split de array public static int[] readInts(String cad) { String read[] = cad.split(" "); int res[] = new int[read.length]; for (int i = 0; i < read.length; i++) { res[i] = Integer.parseInt(read[i]); } return res; } public static boolean isNumber(StringBuilder s) { char p[] = s.toString().toCharArray(); if (s.length() == 0) return false; if (p[0] == '0' && s.length() == 1) return true; if (s.length() == 1 && p[0] >= '0' && p[0] <= '9') return true; if (s.length() > 1) { if (p[0] == '0') return false; for (int i = 0; i < s.length(); i++) { if (p[i] < '0' || p[i] > '9') return false; } return true; } return false; } public static void main(String[] args) throws IOException { long inicio = System.currentTimeMillis(); StringBuilder out = new StringBuilder(); BufferedReader in; File archivo = new File("entrada"); if (archivo.exists()) in = new BufferedReader(new FileReader(archivo)); else in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); char s[] = line.toCharArray(); StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); StringBuilder temp = new StringBuilder(); int acount = 0; int bcount = 0; for (int i = 0; i < s.length; i++) { if (s[i] == ',' || s[i] == ';') { if (isNumber(temp)) { if (acount > 0) a.append(","); a.append(temp); acount++; } else { if (bcount > 0) b.append(","); b.append(temp); bcount++; } temp = new StringBuilder(); } else { temp.append(s[i]); } } if (isNumber(temp)) { if (acount > 0) a.append(","); a.append(temp); acount++; } else { if (bcount > 0) b.append(","); b.append(temp); bcount++; } if (acount == 0) out.append("-\n"); else out.append("\"" + a + "\"\n"); if (bcount == 0) out.append("-\n"); else out.append("\"" + b + "\"\n"); System.out.print(out); if (archivo.exists()) System.out.println("Tiempo transcurrido : " + (System.currentTimeMillis() - inicio) + " milisegundos."); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
2749457b1c9fd80d2c61b3bf6e7b6a09
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A_ExtractNumbers { static boolean debugging = false; static BufferedReader in; static StringTokenizer st; static StringBuilder a, b; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s = new StringBuilder(in.readLine()); a = new StringBuilder(); b = new StringBuilder(); a.append("\""); b.append("\""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ',') { s.setCharAt(i, ';'); } if (i == 0) { continue; } if (s.substring(i - 1, i + 1).equals(";;")) { s.insert(i, "="); } } if (s.charAt(0) == ';') { b.append(","); } if (debugging) { System.out.printf("S: %s\n", s); } st = new StringTokenizer(s.toString(), ";"); while(st.hasMoreTokens()) { String t = st.nextToken(); if (isNumber(t)) { a.append(t + ","); } else { b.append(t.equals("=") ? "," : t + ","); } } if (s.charAt(s.length() - 1) == ';') { b.append(","); } a.replace(a.length() - 1, a.length(), "\""); b.replace(b.length() - 1, b.length(), "\""); if (a.length() == 1) { a = new StringBuilder(); a.append("-"); } if (b.length() == 1) { b = new StringBuilder(); b.append("-"); } System.out.printf("%s\n%s\n", a.toString(), b.toString()); in.close(); } public static boolean isNumber(String x) { if (x.length() > 1 && x.charAt(0) == '0') { return false; } for (int i = 0; i < x.length(); i++) { char c = x.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
3ed92ded902001a95e9a103b96d19d93
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); String line = in.nextLine(); ArrayList<String> words = new ArrayList<>(); int startIndex = 0; for(int i = 0; i < line.length(); i++) { if(line.charAt(i) == ',' || line.charAt(i) == ';') { words.add(line.substring(startIndex, i)); startIndex = i + 1; } } words.add(line.substring(startIndex, line.length())); boolean first = true; for(String word : words) { if(word.matches("[1-9]\\d*|0")) { if(first) { System.out.print("\"" + word); first = false; } else { System.out.print("," + word); } } } if(first) { System.out.println("-"); } else { System.out.println("\""); } first = true; for(String word : words) { if(word.matches("0\\d+|\\w*[a-zA-Z]+\\w*|.*\\..*|")) { if(first) { System.out.print("\"" + word); first = false; } else { System.out.print("," + word); } } } if(first) { System.out.println("-"); } else { System.out.println("\""); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
d51fa62f2c02c431f27b6e95bd0f4a45
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; BufferedWriter out = new BufferedWriter(new OutputStreamWriter( outputStream, "ASCII")); CustomScanner sc = new CustomScanner(inputStream); solve(sc, out); out.flush(); out.close(); } static void solve(CustomScanner sc, BufferedWriter out) throws IOException { String s = sc.nextLine(); StringBuilder a = new StringBuilder(), b = new StringBuilder(), tmp = new StringBuilder(); boolean isInt = true, isBeginning = true; for (int i=0; i<=s.length(); i++) { char c= '\0'; if (i<s.length()) c = s.charAt(i); if (c==',' || c==';' || i==s.length()) { if (tmp.length()==0) isInt= false; if (isInt) { a.append(tmp.toString()); a.append(','); } else { b.append(tmp.toString()); b.append(','); } tmp = new StringBuilder(); isBeginning = true; isInt = true; } else { tmp.append(c); if (c<'0' || c>'9') isInt = false; if (isInt && c>='0' && c<='9') { if (c=='0' && isBeginning==true) { isInt=false; if (i==s.length()-1 || (i<s.length()-1 && (s.charAt(i+1)==',' || s.charAt(i+1)==';'))) isInt = true; } } isBeginning = false; } } if (a.length()>0) { out.write("\""); a.deleteCharAt(a.length()-1); out.write(a.toString()); out.write("\""); } else out.write("-"); out.newLine(); if (b.length()>0) { out.write("\""); b.deleteCharAt(b.length()-1); out.write(b.toString()); out.write("\""); } else out.write("-"); out.newLine(); } static class CustomScanner { BufferedReader br; StringTokenizer st; public CustomScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } private String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
6db77dfd59dc8ab242cb371b4fb97dcb
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.regex.Pattern; public class P600A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.next(); int start = 0; int type = 1; StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); a.append('"'); b.append('"'); char[] arr = str.toCharArray(); int aCnt = 0; int bCnt = 0; Pattern pattern = Pattern.compile("0|[1-9][0-9]*"); ArrayList<String> strings = new ArrayList<>(); for (int i = 0; i < arr.length; i++) { int c = arr[i]; if (c == ';' || c == ',') { strings.add(new String(arr, start, i - start)); start = i + 1; } } if (arr[arr.length - 1] == ';' ||arr[arr.length - 1] == ',') { strings.add(new String("")); } else { strings.add(new String(arr, start, arr.length - start)); } for (String string : strings) { if (pattern.matcher(string).matches()) { if (aCnt > 0) { a.append(','); } aCnt++; a.append(string); } else { if (bCnt > 0) { b.append(','); } bCnt++; b.append(string); } } a.append('"'); b.append('"'); System.out.println(aCnt == 0 ? "-" : a.toString()); System.out.println(bCnt == 0 ? "-" : b.toString()); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
9ba1fb32b51cd60fbf04507f7c9d8916
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Nov 27, 2015 | 4:06:13 PM * <pre> * <u>Description</u> * * </pre> * * @author Essiennta Emmanuel (colourfulemmanuel@gmail.com) */ public class ProblemA{ void solve(String string){ List<String> strings = new ArrayList<>(); List<String> numbers = new ArrayList<>(); char[] s = new char[(int)1e5]; int curr = 0; boolean isString = true; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); if (ch == ';' || ch == ',') { if (isString) strings.add(String.valueOf(s, 0, curr)); else numbers.add(String.valueOf(s, 0, curr)); isString = true; curr = 0; }else { s[curr] = ch; if (curr == 0) { if (ch >= '0' && ch <= '9') isString = false; }else if (curr == 1) { if (s[0] == '0' || ch < '0' || ch > '9') isString = true; }else isString |= ch < '0' || ch > '9'; curr++; } } if (isString) strings.add(String.valueOf(s, 0, curr)); else numbers.add(String.valueOf(s, 0, curr)); if (numbers.isEmpty()) System.out.println('-'); else{ System.out.printf("\""); for (int i = 0; i < numbers.size(); i++){ if (i != 0){ System.out.printf(","); } System.out.printf("%s", numbers.get(i)); } System.out.printf("\"\n"); } if (strings.isEmpty()) System.out.println('-'); else{ System.out.printf("\""); for (int i = 0; i < strings.size(); i++){ if (i != 0){ System.out.printf(","); } System.out.printf("%s", strings.get(i)); } System.out.printf("\"\n"); } } public static void main(String[] args){ Scanner sc = new Scanner(System.in); new ProblemA().solve(sc.next()); sc.close(); } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
2910cd4a4513c34db8dd5d367da599ac
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.math.BigInteger; public class A{ public static void main(String[] args){ Reader reader = new Reader(System.in); PrintWriter writer = new PrintWriter(System.out); String splitter = "[,;]"; String sentence = reader.readWord(); String words[] = sentence.split(splitter); StringBuilder numbers = new StringBuilder(); StringBuilder alphabets = new StringBuilder(); for(int i=0;i<sentence.length();){ int index = i; while(index< sentence.length() && sentence.charAt(index) != ';' && sentence.charAt(index) != ','){ index++; } String word = sentence.substring(i,index); try{ if(word.length()==0){ throw new NumberFormatException(); } if(word.length()>1 && word.charAt(0)=='0') throw new NumberFormatException(); BigInteger b = new BigInteger(word); numbers.append(word); numbers.append(','); } catch (NumberFormatException e){ alphabets.append(word); alphabets.append(','); } i = index+1; } if(sentence.endsWith(",") || sentence.endsWith(";")){ alphabets.append(""); alphabets.append(','); } if(numbers.length()>0){ numbers.deleteCharAt(numbers.length()-1); writer.println("\""+numbers.toString()+"\""); } else{ writer.println("-"); } if(alphabets.length()>0){ alphabets.deleteCharAt(alphabets.length()-1); writer.println("\""+alphabets.toString()+"\""); } else { writer.println("-"); } writer.close(); } public static class Reader { BufferedReader br; StringTokenizer st; public Reader(InputStream is){ br = new BufferedReader(new InputStreamReader(is)); } public String readWord(){ if(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){} } return st.nextToken(); } public int readInt(){ return Integer.parseInt(readWord()); } public long readLong(){ return Long.parseLong(readWord()); } public float readFloat(){ return Float.parseFloat(readWord()); } public double readDouble(){ return Double.parseDouble(readWord()); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
eb0cf54f489225faa9974d21fba7da71
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.math.BigInteger; public class A{ public static void main(String[] args){ Reader reader = new Reader(System.in); PrintWriter writer = new PrintWriter(System.out); String splitter = "[,;]"; String sentence = reader.readWord(); String words[] = sentence.split(splitter); StringBuilder numbers = new StringBuilder(); StringBuilder alphabets = new StringBuilder(); for(int i=0;i<sentence.length();){ int index = i; boolean isAlphabet = false; while(index< sentence.length() && sentence.charAt(index) != ';' && sentence.charAt(index) != ','){ if(!isAlphabet){ if(!Character.isDigit(sentence.charAt(index))){ isAlphabet = true; } } index++; } String word = sentence.substring(i,index); if(word.length()==0){ isAlphabet = true; } if(word.length()>1 && word.charAt(0)=='0') isAlphabet = true; if(isAlphabet){ alphabets.append(word); alphabets.append(','); } else { numbers.append(word); numbers.append(','); } i = index+1; } if(sentence.endsWith(",") || sentence.endsWith(";")){ alphabets.append(""); alphabets.append(','); } if(numbers.length()>0){ numbers.deleteCharAt(numbers.length()-1); writer.println("\""+numbers.toString()+"\""); } else{ writer.println("-"); } if(alphabets.length()>0){ alphabets.deleteCharAt(alphabets.length()-1); writer.println("\""+alphabets.toString()+"\""); } else { writer.println("-"); } writer.close(); } public static class Reader { BufferedReader br; StringTokenizer st; public Reader(InputStream is){ br = new BufferedReader(new InputStreamReader(is)); } public String readWord(){ if(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){} } return st.nextToken(); } public int readInt(){ return Integer.parseInt(readWord()); } public long readLong(){ return Long.parseLong(readWord()); } public float readFloat(){ return Float.parseFloat(readWord()); } public double readDouble(){ return Double.parseDouble(readWord()); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
20108454372611b38bb6519a9cd9c16f
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.math.BigInteger; public class A{ public static void main(String[] args){ Reader reader = new Reader(System.in); PrintWriter writer = new PrintWriter(System.out); String splitter = "[,;]"; String sentence = reader.readWord(); String words[] = sentence.split(splitter); StringBuilder numbers = new StringBuilder(); StringBuilder alphabets = new StringBuilder(); for(int i=0;i<sentence.length();){ int index = i; boolean isAlphabet = false; while(index< sentence.length() && sentence.charAt(index) != ';' && sentence.charAt(index) != ','){ if(!isAlphabet){ if(!Character.isDigit(sentence.charAt(index))){ isAlphabet = true; } } index++; } String word = sentence.substring(i,index); try{ if(isAlphabet) throw new NumberFormatException(); if(word.length()==0){ throw new NumberFormatException(); } if(word.length()>1 && word.charAt(0)=='0') throw new NumberFormatException(); numbers.append(word); numbers.append(','); } catch (NumberFormatException e){ alphabets.append(word); alphabets.append(','); } i = index+1; } if(sentence.endsWith(",") || sentence.endsWith(";")){ alphabets.append(""); alphabets.append(','); } if(numbers.length()>0){ numbers.deleteCharAt(numbers.length()-1); writer.println("\""+numbers.toString()+"\""); } else{ writer.println("-"); } if(alphabets.length()>0){ alphabets.deleteCharAt(alphabets.length()-1); writer.println("\""+alphabets.toString()+"\""); } else { writer.println("-"); } writer.close(); } public static class Reader { BufferedReader br; StringTokenizer st; public Reader(InputStream is){ br = new BufferedReader(new InputStreamReader(is)); } public String readWord(){ if(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){} } return st.nextToken(); } public int readInt(){ return Integer.parseInt(readWord()); } public long readLong(){ return Long.parseLong(readWord()); } public float readFloat(){ return Float.parseFloat(readWord()); } public double readDouble(){ return Double.parseDouble(readWord()); } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
310073f2b20a6b6d73277faed1a1baf8
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.util.Scanner; public class ExtractNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); StringBuilder sub = new StringBuilder(""); StringBuilder a = new StringBuilder(""); StringBuilder b = new StringBuilder(""); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ';' && str.charAt(i) != ',') { sub.append(str.charAt(i)); } else { if (allIntegers(sub)) a.append(sub.append(",")); else b.append(sub.append(",")); sub.delete(0,sub.length()); } } if (allIntegers(sub)) a.append(sub.append(",")); else b.append(sub.append(",")); //System.out.println("\"" + a + "\""); //System.out.println("\"" + b + "\""); if (a.length() > 0) System.out.println("\"" + a.substring(0,a.length()-1) + "\""); else System.out.println("-"); if (b.length() > 0) System.out.println("\"" + b.substring(0,b.length()-1) + "\""); else System.out.println("-"); } public static boolean allIntegers(StringBuilder s) { if (s.length() == 1) { if (s.charAt(0) < '0' || s.charAt(0) > '9') return false; } else if (s.length() > 1) { if (s.charAt(0) <= '0' || s.charAt(0) > '9') { return false; } for (int i = 1; i < s.length(); i++) { if (s.charAt(i) < '0' || s.charAt(i) > '9') { return false; } } } else return false; return true; } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
7195c5fb9c8d96d9b39dfcbffcb3dc1b
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Solution { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s = new StringBuilder(br.readLine()); s.append(";"); StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); for (int i = 0; i < s.length(); i++) { StringBuilder temp = new StringBuilder(); int j = i; boolean flag = false; for (; j < s.length(); j++) { if (s.charAt(j) != ',' && s.charAt(j) != ';') { temp.append(s.charAt(j)); if (s.charAt(j) == '.') flag = true; if (s.charAt(j) == 48 || s.charAt(j) == 49 || s.charAt(j) == 50 || s.charAt(j) == 51 || s.charAt(j) == 52 || s.charAt(j) == 53 || s.charAt(j) == 54 || s.charAt(j) == 55 || s.charAt(j) == 56 || s.charAt(j) == 57) { } else { flag = true; } } else { if (flag) { b.append(temp); b.append(","); } else { if (temp.length() == 0) { b.append(temp); b.append(","); } else if (temp.charAt(0) == 48) { if (temp.length() == 1) { a.append(temp); a.append(","); } else { b.append(temp); b.append(","); } } else { a.append(temp); a.append(","); } } break; } } i = j; } if (a.length() == 0) { System.out.println("-"); } else { a.deleteCharAt(a.length() - 1); System.out.println("\"" + a + "\""); } if (b.length() == 0) { System.out.println("-"); } else { b.deleteCharAt(b.length() - 1); System.out.println("\"" + b + "\""); } } public static int check(StringBuilder b) { try { int a = Integer.parseInt(b.toString()); return a; } catch (NumberFormatException e) { // e.printStackTrace(); return -1; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
6f16932e06a1dbf26e0286cdc620e701
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
/* DISCLAIMER : THIS IS THE WORST CODE WRITTEN BY ME , I REGRET IT COMPLETELY. I WAS VERY FRUSTRATED WHEN I TYPED THIS SHIT , SO PLEASE FORGIVE ME. */ import java.util.*; import java.io.*; import java.math.BigInteger; public class ExtractNumbers { static boolean isNumeric(String str) { try { BigInteger a = new BigInteger(str); if(str.length()>1 && str.startsWith("0")) return false; else return true; } catch(NumberFormatException e) { return false; } } public static void main(String args[]) { MyScanner2 s1=new MyScanner2(); PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out), true); //Close the output stream after use String str=s1.next(); Scanner scan = new Scanner(str); StringBuffer a = new StringBuffer(); StringBuffer b = new StringBuffer(); scan.useDelimiter(",|;"); String curr = null; int zero = 0; int blen=0; int ct=0; boolean up=false,down=false; while(scan.hasNext()) { curr = scan.next(); if(isNumeric(curr)) { if(a.length()==0 ) a.append(curr); else a.append(","+curr); } else { if(curr.length()==0) { zero++; } if(blen==0) b.append(curr); else b.append(","+curr); blen++; } } if(a.length() == 0) out.println("-"); else out.println("\""+a+"\""); if(str.startsWith(",") || str.startsWith(";")) { up=true; } if(str.endsWith(";") || str.endsWith(",")) { down = true; } if(up&(!down)) { if(blen==0) out.println("\"\""); else out.println("\","+b+"\""); out.close(); return; } if((!up)&down) { if(blen==0) out.println("\"\""); else out.println("\""+b+","+"\""); out.close(); return; } if(up&down) { if(blen==0) out.println("\",\""); else out.println("\","+b+",\""); out.close(); return; } if(b.length() == 0) { if(zero!=0) out.println("\"\""); else out.println("-"); } else out.println("\""+b+"\""); out.close(); } static class MyScanner2 { BufferedReader br; StringTokenizer st; public MyScanner2() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
9f0aa454d22287ac5f4e398f27705523
train_001.jsonl
1448636400
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
256 megabytes
/* public class ExtractNumbers { } */ import java.util.*; import java.io.*; import java.math.BigInteger; public class ExtractNumbers { static boolean isNumeric(String str) { try { BigInteger a = new BigInteger(str); if(str.length()>1 && str.startsWith("0")) return false; else return true; } catch(NumberFormatException e) { return false; } } public static void main(String args[]) { MyScanner2 s1=new MyScanner2(); PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out), true); //Close the output stream after use String str=s1.next(); Scanner scan = new Scanner(str); StringBuffer a = new StringBuffer(); StringBuffer b = new StringBuffer(); scan.useDelimiter(",|;"); String curr = null; int zero = 0; int blen=0; int ct=0; boolean up=false,down=false; while(scan.hasNext()) { curr = scan.next(); if(isNumeric(curr)) { if(a.length()==0 ) a.append(curr); else a.append(","+curr); } else { if(curr.length()==0) { zero++; } if(blen==0) b.append(curr); else b.append(","+curr); blen++; } } if(a.length() == 0) out.println("-"); else out.println("\""+a+"\""); if(str.startsWith(",") || str.startsWith(";")) { up=true; } if(str.endsWith(";") || str.endsWith(",")) { down = true; } if(up&(!down)) { if(blen==0) out.println("\"\""); else out.println("\","+b+"\""); out.close(); return; } if((!up)&down) { if(blen==0) out.println("\"\""); else out.println("\""+b+","+"\""); out.close(); return; } if(up&down) { if(blen==0) out.println("\",\""); else out.println("\","+b+",\""); out.close(); return; } if(b.length() == 0) { if(zero!=0) out.println("\"\""); else out.println("-"); } else out.println("\""+b+"\""); out.close(); } static class MyScanner2 { BufferedReader br; StringTokenizer st; public MyScanner2() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } } }
Java
["aba,123;1a;0", "1;;01,a0,", "1", "a"]
2 seconds
["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""]
NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".
Java 7
standard input
[ "implementation", "strings" ]
ad02cead427d0765eb642203d13d3b99
The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
1,600
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
standard output
PASSED
326280dedadeff8522ad81ea5a2376dc
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class D { static int[][] startFromColor(int n, int m, int[] a, int[] b, int color) { int[] arr = new int[n + m], c = new int[n + m]; int pa = 0, pb = 0; while (pa < n || pb < m) { boolean done = false; while (!done) { done = true; if (pa < n && a[pa] == color) { done = false; arr[pa + pb] = pa + 1; c[pa + pb] = color; pa++; } if (pb < m && b[pb] == color) { done = false; arr[pa + pb] = pb + n + 1; c[pa + pb] = color; pb++; } } color = 1 - color; } int[][] res = new int[2][]; res[0] = arr; ArrayList<Integer> opList = new ArrayList<>(); for (int i = 0; i < c.length - 1; i++) { if (c[i] != c[i + 1]) opList.add(i + 1); } if ((c[0] + opList.size()) % 2 == 1) opList.add(c.length); res[1] = new int[opList.size()]; for (int i = 0; i < res[1].length; i++) { res[1][i] = opList.get(i); } return res; } static void solve() { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int m = nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] = nextInt(); } int[][] res0 = startFromColor(n, m, a, b, 0); int[][] res1 = startFromColor(n, m, a, b, 1); print(res0[1].length < res1[1].length ? res0 : res1); } static void print(int[][] res) { for (int i = 0; i < res[0].length; i++) { writer.print(res[0][i] + " "); } writer.println(); writer.println(res[1].length); for (int v : res[1]) { writer.print(v + " "); } } public static void main(String[] args) throws Exception { reader = new BufferedReader(new FileReader("input.txt")); writer = new PrintWriter("output.txt"); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
b5adf5231797c25740ae371206d1ee35
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { new Main().run(); } catch (Throwable e) { e.printStackTrace(); exit(999); } } }, "1", 1 << 23).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); in.close(); out.close(); } private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); int m = nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) b[i] = nextInt(); ans = new int[n + m]; int mn1 = solve(a, b); int mn2 = solve(b, a); if (mn1 <= mn2) print(a, b, 0, n); else print(b, a, n, 0); } int[] ans; void print(int[] a, int[] b, int add1, int add2) { int p1 = 0; int p2 = 0; int cur = a[0]; int cnt = 0; boolean blank = false; while (p1 < a.length || p2 < b.length) { if (p1 + p2 != 0) ans[cnt++] = (p1 + p2); while (p1 < a.length && a[p1] == cur) { if (blank) out.print(' '); else blank = true; out.print(p1 + add1 + 1); p1++; } while (p2 < b.length && b[p2] == cur) { if (blank) out.print(' '); else blank = true; out.print(p2 + add2 + 1); p2++; } cur ^= 1; } ans[cnt++] = p1 + p2; cnt -= cur; out.println(); out.println(cnt); for (int i = 0; i < cnt; i++) { if (i != 0) out.print(' '); out.print(ans[i]); } out.println(); } int solve(int[] a, int[] b) { int p1 = 0; int p2 = 0; int cur = a[p1]; int ret = 0; while (p1 < a.length || p2 < b.length) { ret++; while (p1 < a.length && a[p1] == cur) p1++; while (p2 < b.length && b[p2] == cur) p2++; cur ^= 1; } ret -= cur; return ret; } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } 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()); } 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; } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
c7c4bde00bbe2d375b4519dee2d7e873
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.*; import java.util.*; public class ACMICPC { FastScanner in; PrintWriter out; void solve() { 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[] b = new int[m]; for (int i = 0; i < m; i++) b[i] = in.nextInt(); int[] ans = new int[n + m]; int need = 0; int it1 = n - 1; int it2 = m - 1; int st = 0; while (it1 >= 0 || it2 >= 0) { while (it1 >= 0 && a[it1] == need) ans[st++] = it1--; while (it2 >= 0 && b[it2] == need) ans[st++] = n + (it2--); need = 1 - need; } int[] ans2 = new int[n + m]; for (int i = 0; i < n + m; i++) ans2[i] = 1 + ans[n + m - i - 1]; for (int i = 0; i < n + m; i++) out.print(ans2[i] + " "); for (int i = 0; i < n + m; i++) if (ans2[i] <= n) ans2[i] = a[ans2[i] - 1]; else ans2[i] = b[ans2[i] - 1 - n]; ArrayList<Integer> answ = new ArrayList<Integer>(); int last = ans2[0]; for (int i = 0; i < n + m; i++) if (ans2[i] != last) { answ.add(i); last = ans2[i]; } if (last != 0) answ.add(n + m); out.println(); out.println(answ.size()); for (int i = 0; i < answ.size(); i++) out.print(answ.get(i) + " "); } void run() { try { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new ACMICPC().run(); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
24955c6586bb762cfe3df0add842d3e7
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.util.List; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Crash */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = in.readIntArray(n); int m = in.readInt(); int[] b = in.readIntArray(m); int[] c = new int[n + m + 1]; c[n + m] = 0; int cur = 0; int p1 = n - 1; int p2 = m - 1; int t = 0; int p = n + m - 1; while (p1 >= 0 || p2 >= 0) { if (t == 0) { if (p1 >= 0 && (a[p1] == cur || p2 == -1)) { cur = a[p1]; c[p --] = p1 --; } else { cur = b[p2]; t = 1; c[p --] = (p2 --) + n; //cur = 1 - cur; } } else { if (p2 >= 0 && (b[p2] == cur || p1 == -1)) { cur = b[p2]; c[p --] = (p2 --) + n; } else { t = 0; cur = a[p1]; c[p --] = p1 --; //cur = 1 - cur; } } //cur = c[p + 1]; } for (int i = 0; i < n + m; i ++) out.print((c[i] + 1) + " "); out.printLine(); List<Integer> op = new ArrayList<Integer>(); for (int i = 0; i < n + m; i ++) { int x = (c[i] < n) ? a[c[i]] : b[c[i] - n]; int y = 0; if (i + 1 < n + m) y = (c[i + 1] < n) ? a[c[i + 1]] : b[c[i + 1] - n]; if (x != y) op.add(i); } out.printLine(op.size()); for (int x : op) out.print((x + 1) + " "); out.printLine(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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 int[] readIntArray(int length) { int[] res = new int[length]; for (int i = 0; i < length; i ++) res[i] = readInt(); return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
569b4540a17c80041ec024b867808dc6
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class D { BufferedReader in; StringTokenizer str; PrintWriter out; String SK; String next() throws IOException { while ((str == null) || (!str.hasMoreTokens())) { SK = in.readLine(); if (SK == null) return null; str = new StringTokenizer(SK); } return str.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } ArrayList<Integer> res = new ArrayList<Integer>(); int get(int add, int st, int[] a) { if (st >= a.length) { return 0; } int j = st; while (j < a.length && a[j] == a[st]) { res.add(j + add); j++; } return j - st; } ArrayList<Integer> calc(int n, int[] a, int m, int[] b, boolean fl) { res = new ArrayList<Integer>(); int t1 = 0; int t2 = 0; if (a[0] != b[0]) { if (fl) { t1 += get(0, t1, a); } else { t2 += get(n, t1, b); } } while (t1 < n || t2 < m) { t1 += get(0, t1, a); t2 += get(n, t2, b); } res.add(n + m); return (ArrayList<Integer>) res.clone(); } int count(ArrayList<Integer> res, int n, int[] a, int m, int[] b) { int[] col = new int[n + m + 1]; for (int i = 0; i < n; i++) { col[i] = a[i]; } for (int i = n; i < n + m; i++) { col[i] = b[i - n]; } col[n + m] = 0; int sum = 0; for (int i = 1; i <= n + m; i++) { if (col[res.get(i)] != col[res.get(i - 1)]) { sum++; } } return sum; } void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int m = nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] = nextInt(); } ArrayList<Integer> c1 = calc(n, a, m, b, true); ArrayList<Integer> c2 = calc(n, a, m, b, false); if (count(c1, n, a, m, b) > count(c2, n, a, m, b)) { res = c2; } else { res = c1; } for (int i : res) { if (i != n + m) { out.print((i + 1) + " "); } } out.println(); int[] col = new int[n + m + 1]; for (int i = 0; i < n; i++) { col[i] = a[i]; } for (int i = n; i < n + m; i++) { col[i] = b[i - n]; } col[n + m] = 0; ArrayList<Integer> rev = new ArrayList<Integer>(); for (int i = 1; i <= n + m; i++) { if (col[res.get(i)] != col[res.get(i - 1)]) { rev.add(i); } } out.println(rev.size()); for (int i : rev) { out.print(i + " "); } } void run() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); out.close(); } public static void main(String[] args) throws IOException { new D().run(); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
493ecbe2da3a4b0d3ab54b18bb596435
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class ProblemD { public static void main(String[] args) throws IOException { // Scanner in = new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new FileWriter("output.txt")); 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[] b = new int[m]; for (int i = 0 ; i < m ; i++) { b[i] = in.nextInt(); } int[] rev = new int[n+m]; int idx = n+m-1; int bi = m-1; int ai = n-1; int expected = 0; List<Integer> turn = new ArrayList<Integer>(); while (bi >= 0 || ai >= 0) { while (ai >= 0 && a[ai] == expected) { rev[idx] = ai+1; ai--; idx--; } while (bi >= 0 && b[bi] == expected) { rev[idx] = n+bi+1; bi--; idx--; } expected = 1 - expected; if (idx >= 0) { turn.add(idx); } } StringBuilder first = new StringBuilder(); for (int i = 0 ; i < n + m ; i++) { first.append(" ").append(rev[i]); } StringBuilder second = new StringBuilder(); for (int i = turn.size() - 1 ; i >= 0 ; i--) { second.append(" ").append(turn.get(i)+1); } out.println(first.substring(1)); out.println(turn.size()); if (turn.size() >= 1) { out.println(second.substring(1)); } out.flush(); out.close(); } public static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
33a08cdb4cc7918abae723625e6b6be2
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); int m = nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) b[i] = nextInt(); ArrayList<Integer> res0 = new ArrayList<>(); ArrayList<Integer> runs0 = new ArrayList<>(); int last = -1; for (int i = 0, j = 0, c = 0; i < n || j < m; c ^= 1) { int run = 0; while (i < n && a[i] == c) { res0.add(++i); run++; } while (j < m && b[j] == c) { res0.add(n + ++j); run++; } if (run != 0) runs0.add(run); last = c; } if (last == 0) runs0.remove(runs0.size() - 1); ArrayList<Integer> res1 = new ArrayList<>(); ArrayList<Integer> runs1 = new ArrayList<>(); last = -1; for (int i = 0, j = 0, c = 1; i < n || j < m; c ^= 1) { int run = 0; while (i < n && a[i] == c) { res1.add(++i); run++; } while (j < m && b[j] == c) { res1.add(n + ++j); run++; } if (run != 0) runs1.add(run); last = c; } if (last == 0) runs1.remove(runs1.size() - 1); ArrayList<Integer> res, runs; if (runs0.size() <= runs1.size()) { res = res0; runs = runs0; } else { res = res1; runs = runs1; } for (int i = 0; i < res.size(); i++) out.print(res.get(i) + " "); out.println(); out.println(runs.size()); for (int i = 0, outp = 0; i < runs.size(); i++) { outp += runs.get(i); out.print(outp + " "); } out.println(); } D() throws IOException { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); out.close(); } public static void main(String[] args) throws IOException { new D(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
787f10a1ebfe68a6972a2543a061a71f
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class H implements Runnable { private InputReader in; private PrintWriter out; public static void main(String[] args) { new H().run(); } public H() { //in = new InputReader(System.in); out = new PrintWriter(System.out); try {in = new InputReader(new FileInputStream("input.txt")); out = new PrintWriter(new FileOutputStream("output.txt"));} catch (Exception e) {} } int[] order; int[] lengths; int solve(int[] d1, int[] d2, int initial) { int n = d1.length; int m = d2.length; int oi = 0; order = new int[n+m]; lengths = new int[n+m]; int current = initial; int flips = 0; int a = 0; int b = 0; while (a < n || b < m) { if (a < n && d1[a] == current) { order[a+b] = a+1; a += 1; } else if (b < m && d2[b] == current) { order[a+b] = n+b+1; b += 1; } else { current = 1-current; lengths[flips++] = a+b; } } if (current == 1) { lengths[flips++] = n+m; } return flips; } public void run() { int n = in.readInt(); int[] d1 = new int[n]; for (int i = 0; i < n; i++) d1[i] = in.readInt(); int m = in.readInt(); int[] d2 = new int[m]; for (int i = 0; i < m; i++) d2[i] = in.readInt(); int s1 = solve(d1, d2, 0); int s2 = solve(d1, d2, 1); if (s1 < s2) { solve(d1, d2, 0); } else { solve(d1, d2, 1); } for (int i = 0; i < n+m; i++) out.print(order[i]+" "); out.println(); out.println(Math.min(s1,s2)); for (int i = 0; i < Math.min(s1,s2); i++) out.print(lengths[i]+" "); out.println(); out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } 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++]; } 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 c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private 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) { 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 < '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 < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
275d8376278d6d8d708583379a6db964
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } StreamInputReader in = new StreamInputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { int[] A; int[] B; int[] merge; public void solve(int testNumber, StreamInputReader in, PrintWriter out) { int N = in.nextInt(); A = new int[N]; for(int i = 0; i < N; i++) A[i] = in.nextInt(); int M = in.nextInt(); B = new int[M]; for(int i = 0; i < M; i++) B[i] = in.nextInt(); merge = new int[N + M + 1]; int[] A0 = go(0); int[] A1 = go(1); int[] ans; if(A0.length <= A1.length) ans = go(0); else ans = go(1); for(int i = 0; i < N + M; i++) out.print((merge[i] + 1) + " "); out.println(); out.println(ans.length); for(int i = 0; i < ans.length; i++) out.print(ans[i] + " "); } private int[] go(int start) { int N = A.length; int M = B.length; for(int type = start, i = 0, j = N, k = 0; i < N || j - N < M; ) { while(i < N && A[i] == type) merge[k++] = i++; while(j - N < M && B[j - N] == type) merge[k++] = j++; type = 1 - type; } merge[N + M] = N + M; ArrayList<Integer> diff = new ArrayList<Integer>(); for(int i = 0; i < N + M; i++) if(getValue(merge[i]) != getValue(merge[i + 1])) diff.add(i + 1); int[] ret = new int[diff.size()]; for(int i = 0; i < diff.size(); i++) ret[i] = diff.get(i); return ret; } private int getValue(int p) { if(p < A.length) return A[p]; if(p < A.length + B.length) return B[p - A.length]; return 0; } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(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++]; } } abstract class InputReader { public abstract int read(); public int nextInt() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
872164858e48cd45a04b49755fbfc4a6
train_001.jsonl
1350370800
There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.
256 megabytes
/* Codeforces Template */ 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 { static long initTime; static final Random rnd = new Random(7777L); static boolean writeLog = false; public static void main(String[] args) throws IOException { initTime = System.currentTimeMillis(); try { writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777")); } catch (SecurityException e) {} new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); log("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); log("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ void solve() throws IOException { int n1 = nextInt(); int[] a1 = nextIntArray(n1); int n2 = nextInt(); int[] a2 = nextIntArray(n2); int[][] ans1 = solve(a1, a2, 0); int[][] ans2 = solve(a1, a2, 1); int[][] ans = ans1[1].length < ans2[1].length ? ans1 : ans2; printArray(ans[0]); out.println(ans[1].length); printArray(ans[1]); } int[][] solve(int[] a1, int[] a2, int last) { int n1 = a1.length; int n2 = a2.length; int[] merged = new int [n1 + n2]; int[] dir = new int [n1 + n2]; int sz = 0; int p1 = 0; int p2 = 0; while (p1 < n1 && p2 < n2) { if (a1[p1] == a2[p2]) { { // add from 1 merged[sz] = p1 + 1; dir[sz] = last = a1[p1]; sz++; p1++; } { // add from 2 merged[sz] = n1 + p2 + 1; dir[sz] = last = a2[p2]; sz++; p2++; } } else if (a1[p1] == last) { { // add from 1 merged[sz] = p1 + 1; dir[sz] = last = a1[p1]; sz++; p1++; } } else { { // add from 2 merged[sz] = n1 + p2 + 1; dir[sz] = last = a2[p2]; sz++; p2++; } } } while (p1 < n1) { { // add from 1 merged[sz] = p1 + 1; dir[sz] = last = a1[p1]; sz++; p1++; } } while (p2 < n2) { { // add from 2 merged[sz] = n1 + p2 + 1; dir[sz] = last = a2[p2]; sz++; p2++; } } return new int[][] { merged, solve(dir) }; } int[] solve(int[] dir) { int n = dir.length; int gn = 0; int[] gsz = new int [n]; int[] gtp = new int [n]; gn = 1; gsz[0] = 1; gtp[0] = dir[0]; for (int i = 1; i < n; i++) { if (gtp[gn - 1] == dir[i]) { gsz[gn - 1]++; } else { gtp[gn] = dir[i]; gsz[gn] = 1; gn++; } } int last = gn - 1; if (gtp[last] == 0) last--; int[] ret = new int [last + 1]; for (int g = 0; g <= last; g++) { if (g > 0) gsz[g] += gsz[g - 1]; ret[g] = gsz[g]; } return ret; } /*************************************************************** * 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) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; 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) { if (array == null || array.length == 0) return; 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) { if (array == null || array.length == 0) return; 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) { if (collection == null || collection.isEmpty()) return; 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"); } static void chk(boolean f) { if (!f) throw new RuntimeException("Assert failed"); } static void chk(boolean f, String format, Object ... args) { if (!f) throw new RuntimeException(String.format(format, args)); } static void log(String format, Object ... args) { if (writeLog) System.err.println(String.format(Locale.US, format, args)); } }
Java
["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"]
2 seconds
["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"]
null
Java 7
input.txt
[ "constructive algorithms", "greedy" ]
f1a312a21d600cf9cfff4afeca9097dc
The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.
2,000
In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105.
output.txt
PASSED
417460457f05f964e50e71ccd3c0929e
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.*; public class GoodWork { static Scanner in =new Scanner(System.in); public static void main(String[] args) { int n=in.nextInt(); boolean B=false; int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=in.nextInt(); if(a[i]!=1)B=true; } Arrays.sort(a); if(B){ System.out.print(1+" "); for(int i=0;i<n-1;i++){System.out.print(a[i]+" ");} return;} for(int i=0;i<n-1;i++){System.out.print(a[i]+" ");} System.out.println("2"); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
209f1aaef8363057644188cc71b5faa3
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); //Main public static void main(String args[]) { int test=1; //test=sc.nextInt(); while(test-->0) { int n=sc.nextInt(),a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.sort(a); if(a[n-1]==1) a[n-1]=2; else a[n-1]=1; Arrays.sort(a); for(int x: a) out.print(x+" "); } out.flush(); out.close(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
5ee4ab4b1f2c853f1c8bf2515c50276f
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Main { public static InputReader in; public static PrintWriter pw; public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } }, "1", 1 << 26).start(); } static ArrayList<Integer> g[]; static ArrayList<Integer> h[]; static boolean visited[]; static int[] parent; static int par[]; static int degree[]; static int edjes=0; static int start=-1; static int end=-1; static int Total=0; static int time1[]; static int time2[]; static int glob=0; static int[] ans; static boolean vis2[][]; //static long sum1=0; //static long val[]; static ArrayList<Integer> levels[]; static int max=0; static int lev=1; static ArrayList<Integer> nodes[]; static ArrayList<Integer> values[]; static int depth[]; static boolean found=false; // static long sm[]; static int sum1=0; static int pre[][]; static int subtree[]; static int cnt=0; static HashMap<String,Integer> hm; static int sm[]; static int size[]; static long mul[]; static long d[]=new long[1000000]; static int tot=0; static long highest=(long)1e9; static boolean bit=false; static Stack<Integer> tt=new Stack(); static HashSet<Character> set; static long fact[],num[]; static long MOD=1000000007; static int value[];static int premen[]; static int count=0,index=0; static double ans11[]; static int price[]; static ArrayList<String> hp[][]; static boolean visit[][]; static int cnu[]=new int[1000001]; static int label=1; static int his[][]; static int size1=0; static int up[],down[]; static int TotalUp=0; static long dist[]; // static HashMap<String,Integer> hm1=new HashMap(); // static HashMap<Integer,Integer> hm2=new HashMap(); static TreeSet<Long> set1=new TreeSet(); static long DP[][][]=new long[20][200][1500]; static int t=-1,n=-1; static int two[],min[],r[]; static int total[];static int black[]; static int Parent[]; static int max2[]; // static int tin[],tout[],a[]; public static void solve() throws FileNotFoundException{ in = new InputReader(System.in); pw = new PrintWriter(System.out); /* String p=in.readString(); char c[]=p.toCharArray(); int z[]=new int[p.length()]; z[0]=0; int left=0; int right=0; for(int i=1;i<p.length();i++) { if(i>right) { left=right=i; while(right<p.length()&&c[right]==c[right-left]) right++; z[i]=right-left; right--; } else { int k=i-left; if(z[k]<right-i+1) { z[i]=z[k]; } else { left=i; while(right<p.length()&&c[right]==c[right-left]) right++; z[i]=right-left; right--; } } }*/ int n=in.nextInt(); int a[]=in.nextIntArray(n); if(n==1) { if(a[0]==1) { System.out.println(2); return; } System.out.println(1); return; } int max=0; for(int i=0;i<n;i++) max=Math.max(max,a[i]); if(max!=1) { for(int i=0;i<n;i++) { if(a[i]==max){ a[i]=1; break; } } } else { a[0]=2; } Arrays.sort(a); for(int i=0;i<n;i++) System.out.print(a[i]+" "); } public static boolean check(int a[][],int b[][],int n,int m) { for(int k=0;k<n;k++) { for(int l=0;l<m;l++) { if(a[k][l]!=b[k][l]) { return false; //break; } } } return true; } public static void bfs(int x) { visited[x]=true; Queue<Integer> Q=new LinkedList<Integer>(); Q.add(x); while(!Q.isEmpty()) { int count=Q.size(); while(count>0) { int p=Q.poll(); visited[p]=true; for(int y:g[p]) { if(!visited[y]) { Q.add(y); } } count--; } } } public static void depth(int curr,int parent) { visited[curr]=true; for(int x:g[curr]) { if(!visited[x]) { depth[x]=depth[curr]+1; depth(x,curr); } } } static int Par[]=new int[202]; public static void Height(int cur,int par){ Par[cur]=par; visited[cur]=true; int t=0; for(int x:g[cur]) { if(!visited[x]) { t++; Height(x,cur); high[cur]=Math.max(high[cur], high[x]+1); } } if(t==0) { high[cur]=0; } } static int dia[]=new int[202]; static int high[]=new int[292]; public static void Diameter(int curr,int parent) { visited[curr]=true; int trees=0; ArrayList<Integer> set=new ArrayList(); for(int x:g[curr]) { if(!visited[x]) { trees++; Diameter(x,curr); dia[curr]=Math.max(dia[curr],high[x]); set.add(high[x]); } } if(set.size()>=2) { Collections.sort(set,Collections.reverseOrder()); dia[curr]=Math.max(dia[curr],set.get(0)+set.get(1)+2); } else if(set.size()>0) { dia[curr]=Math.max(dia[curr],set.get(0)+1); } if(trees==0) { dia[curr]=0; } } public static boolean IsPal(String s) { char c[]=s.toCharArray(); for(int i=0;i<c.length/2;i++) { if(c[i]!=c[s.length()-1-i]) return false; } return true; } public static void Merge(long[] a,int p,int r){ if(p<r){ int q = (p+r)/2; Merge(a,p,q); Merge(a,q+1,r); Merge_Array(a,p,q,r); } } public static void Merge_Array(long a[],int p,int q,int r){ long b[] = new long[q-p+1]; long c[] = new long[r-q]; for(int i=0;i<b.length;i++) b[i] = a[p+i]; for(int i=0;i<c.length;i++) c[i] = a[q+i+1]; int i = 0,j = 0; for(int k=p;k<=r;k++){ if(i==b.length){ a[k] = c[j]; j++; } else if(j==c.length){ a[k] = b[i]; i++; } else if(b[i]<c[j]){ a[k] = b[i]; i++; } else{ a[k] = c[j]; j++; } } } public static void dfs1(int curr,int parent) { visited[curr]=true; for(int x:g[curr]) { if(x==parent)continue; depth[x]=depth[curr]+1; up[x]=up[curr]; if(h[x].contains(curr)){ up[x]++; TotalUp++; } dfs1(x,curr); } } public static void dfs(int curr,int Parent) { visited[curr]=true; size[curr]=1; parent[curr]=Parent; count++; if(value[curr]>0) { index=value[curr]; } for(int x:g[curr]) { if(!visited[x]) { dfs(x,curr); size[curr]+=size[x]; } } } static long ncr(long a, long b){ if(b>a || b<0) return 0; long f = (fact[(int) a]*modInverse(((fact[(int) b]*fact[(int) (a-b)])%MOD), MOD))%MOD; return f; } static long modInverse(long a, long mOD2){ return power(a, mOD2-2, mOD2); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y/2, m) % m; p = (p * p) % m; return (y%2 == 0)? p : (x * p) % m; } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } public static long power(long a,long b) { long result=1; while(b>0) { if(b%2==1) result*=a; a=a*a; b/=2; } return result; } static class Pair implements Comparable<Pair>{ int l;int r; Pair(int val,int index){ this.l=val; this.r=index; } @Override public int compareTo(Pair o) { return r-o.r; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
7985f60d60f8f629147ed6e2659a3be3
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main1 { 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;} } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); int n=sc.i(); int arr[]=sc.arr(n); Arrays.sort(arr); if(arr[n-1]==1) arr[n-1]=2; else arr[n-1]=1; Arrays.sort(arr); for(int i=0;i<n;i++)out.print(arr[i]+" "); out.flush(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
fe0848e9273e096c2bbadeb4a005f0bd
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CF{public static void main(String[] args){S s=new S();s.s();s.output();}}class S{ void s() { int n = NI(); int[] a = new int[n]; inInt(a, n); Arrays.sort(a); if (n > 1 || a[0] != 1) out("1 "); for (int i = 0; i < n - 2; i++, out(' ')) out(a[i]); if (n == 1 && a[0] == 1 || n > 1 && a[n - 1] == 1) out("2"); else if (n > 1 && a[n - 1] != 1) out(a[n - 2]); } BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));StringTokenizer st=new StringTokenizer("");final long LINF=Long.MAX_VALUE; StringBuilder output=new StringBuilder();final int INF=Integer.MAX_VALUE;void sout(Object x){output.append(x.toString()).append('\n');} void inLong(long[]a,int n){for(int i=0;i<n;i++)a[i]=NL();}int min(int i1,int i2){return i1<i2?i1:i2;}double ND(){return Double.parseDouble(NS());} long min(long i1,long i2){return i1<i2?i1:i2;}int max(int i1,int i2){return i1>i2?i1:i2;}long max(long i1,long i2){return i1>i2?i1:i2;} String NS(){while(!st.hasMoreTokens())try{st=new StringTokenizer(stdin.readLine());}catch(IOException ignored){}return st.nextToken();} int NI(){return Integer.parseInt(NS());}long NL(){return Long.parseLong(NS());}String NLn()throws IOException{return stdin.readLine();} int abs(int x){return x<0?-x:x;}long abs(long x){return x<0?-x:x;}void sout(){output.append('\n');}void out(Object x){output.append(x.toString());} int mod(int x,int mod){return(x+mod)%mod;}void output(){System.out.print(output);}void inInt(int[]a,int n){for(int i=0;i<n;i++)a[i]=NI();} }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
59fede579b56759242d3cc91535b6424
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lpeter83 */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); long[] a = new long[n]; for(int i = 0; i < n; i++) { a[i] = in.readInt(); } Arrays.sort(a); if (allOne(a)) { for(int i = 0; i < n-1; i++) { out.print(1+" "); } out.print(2+" "); } else { for(int i = 0; i < n; i++) { if (i == 0) out.print(1+" "); else out.print(a[i-1]+" "); } } } private boolean allOne(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { if (a[i]!=1) return false; } return true; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
f0215c6dcddf437e00fe33eab7a4e7cc
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class C { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solution() throws IOException { int n = nextInt(); int[] mas = new int[n]; for (int i = 0; i < n; i++) { mas[i] = nextInt(); } Arrays.sort(mas); if (mas[n - 1] == 1) { mas[n - 1] = 2; } else { mas[n - 1] = 1; } Arrays.sort(mas); for (int i = 0; i < n; i++) { System.out.print(mas[i] + " "); } } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.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()); } public static void main(String args[]) throws IOException { new C().solution(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
c6c638ee39ccbf400d5431cd4fb2ce63
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class C { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solution() throws IOException { int n = nextInt(); int[] mas = new int[n]; for (int i = 0; i < n; i++) { mas[i] = nextInt(); } Arrays.sort(mas); if (mas[n - 1] == 1) { mas[n - 1] = 2; } else { mas[n - 1] = 1; } Arrays.sort(mas); for (int i = 0; i < n; i++) { System.out.print(mas[i] + " "); } } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.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()); } public static void main(String args[]) throws IOException { new C().solution(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
95e320323fc97bf03843071d74d9a779
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Algs { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] src = new int[n]; for (int i = 0; i < n; i++) { src[i] = in.nextInt(); } Arrays.sort(src); int[] dest = new int[n]; int curr = src[n - 1]; if (curr == 1) { dest[n - 1] = 2; for (int i = n - 2; i >= 0; i--) { dest[i] = 1; } } else { for (int i = n - 1; i > 0; i--) { curr = src[i]; if (src[i - 1] == curr) { dest[i] = curr; } else { dest[i] = src[i - 1]; } } dest[0] = 1; } for (int i = 0; i < n; i++) { System.out.print(dest[i] + " "); } System.out.println(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
e5b94b03fb0abb0d9e9606467df61364
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.util.*; public class R97D2T136C { public void solve() throws IOException { int n = nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Arrays.sort(a); if (a[n-1] > 1) a[n-1] = 1; else a[n-1] = 2; Arrays.sort(a); for (int i = 0; i < a.length; i++) { writer.print(a[i] + " "); } } // ---------------------------------------------------------------- // public static void main(String[] args) throws FileNotFoundException { new R97D2T136C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { long tbegin = System.currentTimeMillis(); reader = new BufferedReader(new InputStreamReader(System.in)); //reader = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); tokenizer = null; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //writer = new PrintWriter(new FileOutputStream("output.txt")); solve(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
d943f19f01338a06800ba9bf0e69d315
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public BufferedReader input; public PrintWriter output; public StringTokenizer stoken = new StringTokenizer(""); public static void main(String[] args) throws IOException { new Main(); } Main() throws IOException{ /*input = new BufferedReader( new FileReader("input.txt") );*/ input = new BufferedReader( new InputStreamReader(System.in) ); output = new PrintWriter(System.out); /*int a = nextInt(); int c = nextInt(); String ast = ""; String cst = ""; while (a>=3){ ast = a%3+ast; a = a/3; } ast = a + ast; while (c>=3){ cst = c%3+cst; c = c/3; } cst = c + cst; while (ast.length()<cst.length()){ ast = "0" + ast; } while (cst.length()<ast.length()){ cst = "0" + cst; } String bst = ""; for (int i=0; i<cst.length(); i++){ int inc = cst.charAt(i)-48; int ina = ast.charAt(i)-48; bst = bst + (3+inc-ina)%3; } long res = 0; for (int i=0; i<bst.length(); i++){ res += (bst.charAt(i)-48)*(long)Math.pow(3, bst.length()-1-i); } output.print(res);*/ int n = nextInt(); int mas [] = new int [n]; for (int i=0; i<n; i++){ mas[i] = nextInt(); } Arrays.sort(mas); if (mas[n-1]==1){ for (int i=0; i<n-1; i++){ output.print(mas[i]+" "); } output.print("2 "); } else { output.print("1 "); for (int i=0; i<n-1; i++){ output.print(mas[i]+" "); } } output.close(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } private String nextString() throws IOException { while (!stoken.hasMoreTokens()){ String st = input.readLine(); stoken = new StringTokenizer(st); } return stoken.nextToken(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
508c0cd83c88806e94bc5fa00ac2f3c0
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class sample { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; boolean allone = true; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); if (allone && a[i] != 1) allone = false; } if (a.length == 1) { if (allone) System.out.println(2); else System.out.println(1); } else { Arrays.sort(a); StringBuilder sb = new StringBuilder("1"); if (allone) { for (int i = 0; i < a.length - 2; i++) sb.append(" " + a[i]); sb.append(" " + 2); } else { for (int i = 0; i < a.length - 1; i++) sb.append(" " + a[i]); } System.out.println(sb.toString()); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
a27a8dcc279a8f4291b8fd8a8da3ecd7
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class TaskF { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; a[0] = in.nextInt(); int m = 0; int max = a[m]; for (int i = 1; i < n; i++) { a[i] = in.nextInt(); if (a[i] > max) { max = a[i]; m = i; } } if (max == 1) { a[m] = 2; } else { a[m] = 1; } Arrays.sort(a); for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
7359dfa6094cd9291abd824482fa1d28
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.*; public class c { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; boolean ff = true; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (a[i] != 1) { ff = false; } } Arrays.sort(a); for (int i = n - 1; i >= 1; i--) { a[i] = a[i - 1]; } a[0] = 1; if (ff) a[n - 1] = 2; for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
c2dbebc127f646ac377ab2a4b618e24d
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.lang.*; import java.lang.reflect.Array; public class test { public static void main(String[] args) throws Exception { int n = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = nextInt(); } Arrays.sort(a); if(a[n-1] == 1) a[n-1] = 2; else a[n-1] = 1; Arrays.sort(a); for(int i = 0; i < n; i++){ out.print(a[i]+" "); } out.flush(); } private static PrintWriter out = new PrintWriter(System.out); private static BufferedReader inB = new BufferedReader(new InputStreamReader(System.in)); private static StreamTokenizer in = new StreamTokenizer(inB); private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
984282cd4fcd8ba11791b8591062d451
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Solution { public static final String INPUT_FILE = "a.in"; public static final String OUTPUT_FILE = "a.out"; BufferedReader bf; StringTokenizer st; public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String line = bf.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public Solution() throws IOException { //bf = new BufferedReader(new FileReader(new File("a.in"))); bf = new BufferedReader(new InputStreamReader(System.in)); int n = new Integer(next()); int[] m = new int[n]; int max = 0; for(int i = 0; i < n; i ++) { m[i] = new Integer(next()); if (m[i] > m[max]) { max = i; } } if (m[max] == 1) { m[max] = 2; } else { m[max] = 1; } Arrays.sort(m); for(int i = 0; i < n; i ++) { System.out.print(m[i] + " "); } } public static void main(String args[]) throws IOException{ new Solution(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
84e2acfcb9b9471dd1db7fdf04190d1d
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; /** * Replacement * * Little Petya very much likes arrays consisting of n integers, where each of * them is in the range from 1 to 10^9, inclusive. Recently he has received one * such array as a gift from his mother. Petya didn't like it at once. He * decided to choose exactly one element from the array and replace it with * another integer that also lies in the range from 1 to 10^9, inclusive. It is * not allowed to replace a number with itself or to change no number at all. * * After the replacement Petya sorted the array by the numbers' non-decreasing. * Now he wants to know for each position: what minimum number could occupy it * after the replacement and the sorting. * * Input * The first line contains a single integer n (1 <= n <= 10^5), which represents * how many numbers the array has. The next line contains n space-separated * integers — the array's description. All elements of the array lie in the * range from 1 to 10^9, inclusive. * * Output * Print n space-separated integers — the minimum possible values of each array * element after one replacement and the sorting are performed. * * Sample test(s) * Input * 5 * 1 2 3 4 5 * Output * 1 1 2 3 4 * * Input * 5 * 2 3 4 5 6 * Output * 1 2 3 4 5 * * Input * 3 * 2 2 2 * Output * 1 2 2 * * @author Europa */ public class Replacement { private static int[] minimum(int[] array) { Arrays.sort(array); int N = array.length - 1, max = array[N]; for (int i = N; i >= 1; i--) { array[i] = array[i - 1]; } array[0] = 1; if (max == 1) array[N] = 2; return array; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] array = new int[N]; for (int i = 0; i < N; i++) { array[i] = scanner.nextInt(); } int[] results = Replacement.minimum(array); for (int i = 0; i < N; i++) { System.out.print(results[i] + " "); } System.out.println(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
2fc589a21ac86cf5b4dd92fa545ca36e
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { private BufferedReader input; private PrintWriter output; private StringTokenizer stoken; String fin = "input"; String fout = "output"; private void solve() throws IOException { /* int n = nextInt(); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[nextInt()-1] = i; } for (int i=0; i<n; i++) { output.print( (arr[i]+1) + " " ); } */ /* int a = nextInt(); int c = nextInt(); String sa = to3(a); String sc = to3(c); while (sa.length() < sc.length()) sa = "0" + sa; while (sc.length() < sa.length()) sc = "0" + sc; String minus = ""; for (int i=sa.length()-1; i>=0; i--) { int x = Integer.parseInt( (sa.charAt(i)+"") ); int y = Integer.parseInt( (sc.charAt(i)+"") ); int m = y - x; if (m == -1) { m = 2; } else if (m == -2) { m = 1; } minus = String.valueOf(m) + minus; } while (minus.length() > 0 && minus.charAt(0) == '0') { minus = minus.substring(1); } long res = 0; long step = minus.length()-1; for (int i=0; i<minus.length(); i++) { int k = Integer.parseInt( (minus.charAt(i)+"") ) * (int) Math.pow(3, step); step--; res = res + k; } output.print(res); */ int n = nextInt(); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = nextInt(); } Arrays.sort(arr); int count1 = 0; while (count1 < n && arr[count1] == 1) { count1++; } if (count1 > 0) { if (count1 >= 1 && n != 1) { output.print(1 + " "); } for (int i=0; i<n-2; i++) { output.print(arr[i] + " "); } if (count1 == n) { output.print("2"); } else { output.print(arr[n-2]); } } else { output.print("1 "); for (int i=0; i<n-1; i++) { output.print(arr[i] + " "); } } /* Point[] p = new Point[8]; for (int i=0; i<8; i++) { p[i] = new Point(nextInt(), nextInt()); } */ } private String to3(int n) { String res = ""; do { int ost = n % 3; res = String.valueOf(ost) + res; n = n / 3; } while (n >= 3); res = String.valueOf(n) + res; return res; } Main() throws IOException { //input = new BufferedReader(new InputStreamReader(System.in)); //output = new PrintWriter(System.out); //input = new BufferedReader(new FileReader(fin + ".txt")); //output = new PrintWriter(new FileWriter(fout + ".txt")); //input = new BufferedReader(new FileReader(fin + ".txt")); input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); solve(); input.close(); output.flush(); output.close(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextFloat() { return Float.parseFloat(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextToken() { while ((stoken == null) || (!stoken.hasMoreTokens())) { try { String line = input.readLine(); stoken = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return stoken.nextToken(); } public static void main(String[] args) throws IOException { new Main(); } } class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
fabc75abc0c088c39b0a1c36521b9523
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Arrays; import java.util.Scanner; /** * * @author Inquisiter */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int n = in.nextInt(); int nArr[] = new int[n]; boolean check = true; for(int ii=0; ii<n; ii++) { nArr[ii] = in.nextInt(); if(nArr[ii] != 1) check = false; } Arrays.sort(nArr); if(check) { for(int ii=0; ii<n-1; ii++) { System.out.println(nArr[ii]); } System.out.println(2); } else { System.out.println(1); for(int ii=0; ii<n-1; ii++) { System.out.println(nArr[ii]); } } } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
38799c8701cce5cabafb2518b957ccb9
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class TaskC { /** * @param args */ public static void main(String[] args) { TaskC task = new TaskC(); task.read(); task.write(); } int n; ArrayList<Integer> ar = new ArrayList<Integer>(); public void read() { Scanner in = new Scanner(System.in); n = in.nextInt(); for (int i = 0; i < n; i++) { ar.add(in.nextInt()); } in.close(); } public void write() { PrintWriter out = new PrintWriter(System.out); Collections.sort(ar); if (n == 1 && ar.get(0) == 1) { out.print("2 "); } else { out.print("1 "); } for (int i = 1; i < n; i++) { if (ar.get(i) == 1 && (i == n - 1)) { out.print("2 "); } else { out.print(ar.get(i - 1) + " "); } } out.close(); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
5da47747a0b86e996a533d1b6a062eae
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author codeKNIGHT */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n=in.nextInt(),i; int a[]=new int[n]; boolean allone=true; for(i=0;i<n;i++) { a[i]=in.nextInt(); if(a[i]!=1) allone= false; } Arrays.sort(a); for(i=n-1;i>=1;i--) a[i]=a[i-1]; a[0]=1; for(i=0;i<n-1;i++) out.print(a[i]+" "); if(allone) out.println("2"); else out.println(a[n-1]); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output
PASSED
8e9998295d79ad8d65c65e2e3537ea0f
train_001.jsonl
1323443100
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.StringTokenizer; public class C97P3 { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //------------------------------------------------------------------------- //Initializing... new C97P3(); //------------------------------------------------------------------------- //put your code here... :) int n =nextInt(); int [] num = new int[n]; for (int i = 0; i < num.length; i++) { num[i]=nextInt(); } Arrays.sort(num); if(check(num)){w(n);return;} int [] out=new int[n];out[0]=1; for (int i = 1; i < out.length; i++) { out[i]=num[i-1]; } for (int i = 0; i < out.length; i++) { write(out[i]+((i+1==n)?"\n":" ")); } //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } private static void w(int n) { // TODO Auto-generated method stub for (int i = 0; i < n-1; i++) { write("1 "); } writeln("2"); } private static boolean check(int[] num) { // TODO Auto-generated method stub for (int i = 0; i < num.length; i++) { if(num[i]!=1)return false; } return true; } public C97P3() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+"\n"); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } }
Java
["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"]
2 seconds
["1 1 2 3 4", "1 2 3 4 5", "1 2 2"]
null
Java 6
standard input
[ "implementation", "sortings", "greedy" ]
1cd10f01347d869be38c08ad64266870
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
1,300
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
standard output