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
7a8b6476d757dfbf769cd18618402a64
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Main { static int[][] matrix=new int[105][105]; static boolean[][] map=new boolean[105][105]; public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { matrix[i][j]=in.nextInt(); map[i][j]=false; } } int sum=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(map[i][j]==false&&(i==j||i+j==n-1||i==(n-1)/2||j==(n-1)/2)) { sum+=matrix[i][j]; map[i][j]=true; } } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
8433decb24cf25d1cf85f0b8243b97e5
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
//package contest_abbyy_easy; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StreamTokenizer; import java.io.Writer; /** * Date : 30.04.2012 * Time : 9:57:17 * Email : denys.astanin@gmail.com */ public class A2 { public static void main(String[] args) throws IOException { new A2().run(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String nextString() throws IOException { in.nextToken(); return (String) in.sval; } StreamTokenizer in; Writer writer; Reader reader; void run() throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader("src/contest_abbyy_easy/A2.txt"); writer = new OutputStreamWriter(System.out, "ISO-8859-1"); in = new StreamTokenizer(new BufferedReader(reader)); PrintWriter out = new PrintWriter(writer); int n = nextInt(); long sum = 0; boolean[][] was = new boolean[n][n]; long[][] arr = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = nextInt(); } } for (int i = 0; i < n; i++) { if (!was[i][i]) { sum += arr[i][i]; was[i][i] = true; } } for (int i = 0; i < n; i++) { if (!was[(n - 1) /2][i]) { sum += arr[(n - 1) /2][i]; was[(n - 1) /2][i] = true; } if (!was[i][(n - 1) /2]) { sum += arr[i][(n - 1) /2]; was[i][(n - 1) /2] = true; } } for (int i = 0; i < n; i++) { if (!was[i][arr.length - 1 - i]) { sum += arr[i][arr.length - 1 - i]; } } out.println(sum); out.flush(); out.close(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
9f0fb4f68e77314cfc5cba4842c93edf
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StreamTokenizer; import java.io.Writer; /** * Date : 21.04.2012 * Time : 16:48:16 * Email : denys.astanin@gmail.com */ public class e_a { public static void main(String[] args) throws IOException { new e_a().run(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String nextString() throws IOException { in.nextToken(); return (String) in.sval; } StreamTokenizer in; Writer writer; Reader reader; void run() throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader("input/ie_a.txt"); writer = new OutputStreamWriter(System.out, "ISO-8859-1"); in = new StreamTokenizer(new BufferedReader(reader)); PrintWriter out = new PrintWriter(writer); int n = nextInt(); long sum = 0; boolean[][] was = new boolean[n][n]; long[][] arr = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = nextInt(); } } for (int i = 0; i < n; i++) { if (!was[i][i]) { sum += arr[i][i]; was[i][i] = true; } } for (int i = 0; i < n; i++) { if (!was[(n - 1) /2][i]) { sum += arr[(n - 1) /2][i]; was[(n - 1) /2][i] = true; } if (!was[i][(n - 1) /2]) { sum += arr[i][(n - 1) /2]; was[i][(n - 1) /2] = true; } } for (int i = 0; i < n; i++) { if (!was[i][arr.length - 1 - i]) { sum += arr[i][arr.length - 1 - i]; } } out.println(sum); out.flush(); out.close(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
f7d02c1a6493cdc89fbea07244fdb236
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
//package abbyy2.easy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class AS { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[][] a = new int[n][n]; long s = 0; for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ a[i][j] = ni(); } } boolean[][] ma = new boolean[n][n]; for(int i = 0;i < n;i++){ ma[i][i] = true; ma[i][n-1-i] = true; ma[i][(n-1)/2] = true; ma[(n-1)/2][i] = true; } for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ if(ma[i][j]){ s += a[i][j]; } } } out.println(s); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new AS().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
1b8b2100abc1d60b3af06141940a6164
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class GoodMatrixElements { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int total=0; int row,column; int no; row=column=n/2+1; boolean is=false; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { no=sc.nextInt(); if(i==j) is=true; else if((i+j)==(n+1)) is=true; else if(i==row || column==j) is=true; if(is) { // System.out.println(no); total+=no; is=false; } } } System.out.println(total); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
efb61cb68acc2340969763aa51c2b377
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class MatrixGoodElements { public static void main(String[] args) { solve(); } public static void solve() { BufferedReader br = null; InputStreamReader is = null; is = new InputStreamReader(System.in); br = new BufferedReader(is); try { int dimension = Integer.valueOf(br.readLine()); Integer[][] matrix = new Integer[dimension][dimension]; for (int row = 0; row < dimension; ++row) { StringTokenizer strTokenizer = new StringTokenizer(br.readLine(), " "); for (int column = 0; column < dimension; ++column) { matrix[row][column] = Integer.valueOf(strTokenizer.nextToken()); } } int res = 0; int middle = dimension / 2; for (int index = 0; index < dimension; ++index) { res += matrix[index][index]; res += matrix[dimension - index - 1][index]; res += matrix[middle][index]; res += matrix[index][middle]; } res -= 3 * matrix[middle][middle]; System.out.println(res); } catch (Exception e) { e.printStackTrace(); } if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } static int getNod(int num1, int num2) { int n = num1 % num2; num1 = num2; num2 = n; if (n > 0) return getNod(num1, num2); else return num1; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
8e74d1d9c3f56eaf5b1e1852267da9cc
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class GoodMatrixElements { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String st = in.nextLine(); int n = Integer.parseInt(st); int i = 0, j= n/2; int s = 0; for(int a=0;a<n;a++) { st = in.nextLine(); String stv[] = st.split(" "); for(int b=0;b<n;b++) { if((b==i || b==j || b==(n-1-i)) || a==j) s+=Integer.parseInt(stv[b]); } if(a < j) i++; else i--; } System.out.print(s); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
d3ba3b518f7517eac154bffd50cb55ec
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class A { public static void main(String[] args) throws IOException { BufferedReader std = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(std.readLine()); String[][] a = new String[n][n]; boolean[][] b = new boolean[n][n]; int sum = 0; for (int i = 0; i < n; i++) { String s = std.readLine(); String[] ss = s.split(" "); a[i] = ss; } int j = 0; int k = n-1; for (int i = 0; i < n; i++) { if (!b[i][j]) { sum += Integer.parseInt(a[i][j]); b[i][j] = true; } if (!b[i][k]) { sum += Integer.parseInt(a[i][k]); b[i][k] = true; } j++; k--; } int mr = n / 2; for (int i = 0; i < n; i++) { if (!b[i][mr]) { sum += Integer.parseInt(a[i][mr]); b[i][mr] = true; } if (!b[mr][i]){ sum += Integer.parseInt(a[mr][i]); b[mr][i] = true; } } out.println(sum); out.flush(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
0d508dd25692430367a7fc78a0694b78
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class A { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } catch (NullPointerException e) { line=null; } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new A(filePath); } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } public A(String inputFile) { openInput(inputFile); readNextLine(); int ret=0; int N=NextInt(); boolean [] [] p = new boolean [N][N]; for(int i=0; i<N; i++) { readNextLine(); for(int j=0; j<N;j++) { int a=NextInt(); p[i][j]=false; if(i==j)p[i][j]=true; if(i==N-j-1)p[i][j]=true; /*if(i==j+2)p[i][j]=true; if(i==j-2)p[i][j]=true; if(i==N-j+1)p[i][j]=true; if(i==N-j-3)p[i][j]=true;*/ if(i==(N-1)/2)p[i][j]=true; if(j==(N-1)/2)p[i][j]=true; if(p[i][j])ret+=a; //System.out.print(p[i][j]?'X':'.'); } //System.out.println(); } System.out.println(ret); closeInput(); } private class Item implements Comparable<Item> { int cnt,buy,sell; Item (int a, int b, int c) { buy=a; sell=b; cnt=c; } public int compareTo(Item d) { return d.sell-d.buy-(sell-buy); } } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
5b15979d03744bfd8c249d14520e2b97
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class ABBY_2_a { public static void main(String agrs[]){ Scanner in=new Scanner(System.in); int n = in.nextInt(); int a[][]=new int[n][n]; for (int i=0; i<n;i++) for (int j=0; j<n; j++) a[i][j] = in.nextInt(); long sum = 0; boolean t[][]=new boolean[n][n]; for (int i=0; i<n;i++) if (!t[i][i]) {sum += a[i][i];t[i][i] =true;} for (int i=0; i<n; i++) if (!t[i][n-i-1]){ sum+= a[i][n-i-1]; t[i][n-i-1] =true;} for (int i=0; i<n; i++) if (!t[(n-1)/2][i]) { sum+= a[(n-1)/2][i]; t[(n-1)/2][i] = true;} for (int i=0; i<n; i++) if (!t[i][(n-1)/2]){ sum += a[i][(n-1)/2]; t[i][(n-1)/2] = true;} System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
6a55dc24fd3660bcb110200e73e57682
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; import java.util.StringTokenizer; public class A1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int size = sc.nextInt(); int[][] matrix = new int[size][size]; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j ++){ matrix[i][j] = sc.nextInt(); } } int result = 0; int middle = ((int)size / 2); for(int i = 0; i < size; i++){ result += matrix[i][i];//main diagonal if(i != size - i - 1){ result += matrix[i][size - i - 1];//add. diagonal } if(i!= middle){ result += matrix[middle][i];//y result += matrix[i][middle];//x } } System.out.println(result); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
5c2a573e5a30573ed7aea3e1fc032890
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new A(), "", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int n = readInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ a[i][j] = readInt(); } } int sum = 0; boolean[][] used = new boolean[n][n]; for (int i = 0; i < n; i++){ sum += a[i][i]; used[i][i] = true; } for (int i = 0; i < n; i++){ int j = n - 1 - i; if (!used[i][j]){ sum += a[i][j]; used[i][j] = true; } } for (int j = 0; j < n; j++){ if (!used[n/2][j]){ sum += a[n/2][j]; used[n/2][j] = true; } } for (int i = 0; i < n; i++){ if (!used[i][n/2]){ sum += a[i][n/2]; used[i][n/2] = true; } } out.print(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
0b19cb3c39570f6e95ba1471828e0976
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Домашний */ import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException{ int[] res = new int[n]; for(int i = 0; i < n; i++){ res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++){ res[i] = readLong(); } return res; } public static void main(String[] args){ new A().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = readInt(); int[][] a = new int[n][n]; for(int i=0;i < n; i++){ for(int j = 0; j <n; j++){ a[i][j] = readInt(); } } int summ = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i == j){ summ += a[i][j]; continue; } if(i == n-1-j){ summ += a[i][j]; continue; } if(i == n/2){ summ += a[i][j]; continue; } if(j == n/2){ summ += a[i][j]; continue; } } } out.println(summ); } void maxHepify(int[] a, int i, int length){ int l = (i<<1) + 1; int r = (i<<1) + 2; int largest = i; if(l < length && a[l] > a[largest]) largest = l; if(r < length && a[r] > a[largest]) largest = r; if(largest != i){ a[largest] += a[i]; a[i] = a[largest] - a[i]; a[largest] -= a[i]; maxHepify(a, largest, length); } } void buildMaxHeap(int[] a){ for(int i = a.length/2 - 1; i >= 0; i--){ maxHepify(a, i, a.length); } } void heapSort(int[] a){ buildMaxHeap(a); for(int i = a.length - 1; i > 0; i--){ a[i] += a[0]; a[0] = a[i] - a[0]; a[i] -= a[0]; maxHepify(a, 0, i); } } int[] zFunction(char[] s){ int[] z = new int[s.length]; z[0] = 0; for (int i=1, l=0, r=0; i<s.length; ++i) { if (i <= r) z[i] = min (r-i+1, z[i-l]); while (i+z[i] < s.length && s[z[i]] == s[i+z[i]]) ++z[i]; if (i+z[i]-1 > r){ l = i; r = i+z[i]-1; } } return z; } int[] prefixFunction(char[] s){ int[] pr = new int[s.length]; for (int i = 1; i< s.length; ++i) { int j = pr[i-1]; while (j > 0 && s[i] != s[j]) j = pr[j-1]; if (s[i] == s[j]) ++j; pr[i] = j; } return pr; } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } public static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
96d2a978a12d1acdb9e52bcf5510e137
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A_Abba { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n=sc.nextInt(); int a[][]=new int[n+1][n+1]; long sum=0; for (int i = 1; i <=n; i++) { for (int j = 1; j <=n; j++) { a[i][j]=sc.nextInt(); if(i==j) sum+=a[i][j]; } } for (int i = 1; i <=n; i++) { sum+=a[i][n-i+1]; } for (int i = 1; i <=n; i++) { sum+=a[(n-1)/2+1][i]; } for (int i = 1; i <=n; i++) { sum+=a[i][(n-1)/2+1]; } sum-=3*a[(n-1)/2+1][(n-1)/2+1]; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
5562a1a25894a3090121987b20379759
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; public class First{ public static void main(String a[]){ try{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(in.readLine()); int s=(n-1)/2; int sum=0; for(int i=0;i<n;i++){ String z=in.readLine(); String zz[]=z.split(" "); if(i==s){ for(int j=0;j<n;j++)sum+=Integer.parseInt(zz[j]); }else{ sum+=Integer.parseInt(zz[i])+Integer.parseInt(zz[s])+Integer.parseInt(zz[n-1-i]); } } System.out.println(sum); }catch(Exception e){} } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
0b00774fdca2956f2e164c2b7201cf81
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A177 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] a = new int[n][n]; boolean[][] u = new boolean[n][n]; for (int i = 0 ; i < n ; i++) for (int j = 0 ; j < n ; j++) { a[i][j] = in.nextInt(); u[i][j] = false; } int res = 0; for (int i = 0 ; i < n ; i++) { res += a[i][i]; u[i][i] = true; } for (int i = 0 ; i < n ; i++) if (!u[i][n - 1 - i]) { res += a[i][n - i - 1]; u[i][n - i - 1] = true; } int m = n / 2; for (int i = 0 ; i < n ; i++) if (!u[m][i]) { res += a[m][i]; u[m][i] = true; } for (int i = 0 ; i < n ; i++) if (!u[i][m]) { res += a[i][m]; u[i][m] = true; } System.out.println(res); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
13572ad097d46794aca0bd8f29e4f558
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a; long sum = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a = sc.nextInt(); if (i == j || n - i + 1 == j || i == n / 2 + 1 || j == n / 2 + 1) sum += a; } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
4ee943ad30a0ac11a42f5819c29dd2df
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long sum = 0; if (n <= 3) for (int i = 0; i < n * n; i++) sum += sc.nextLong(); else { int p = (n - 1) / 2; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { long t = sc.nextLong(); if (i == j || i == p || j == p || i + j == (n - 1)) sum += t; } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
376207c01f838c41927465971caa2341
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math.*; public class good { public static void main(String args[])throws Exception { Scanner in=new Scanner(System.in); //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("good.in")); //PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("good.out"))); PrintWriter pw = new PrintWriter(System.out); //StringTokenizer st; int n=in.nextInt(); int i,j,k,l; int a[][]=new int[n][n]; if(n==1) { pw.println(in.nextInt()); pw.flush(); System.exit(0); } for(i=0;i<n;i++) { for(j=0;j<n;j++) a[i][j]=in.nextInt(); } int sum=0; for(j=0;j<n;j++) { sum+=a[n/2][j]+a[j][n/2]+a[j][j]+a[j][n-1-j]; } pw.println(sum-3*(a[n/2][n/2])); pw.flush(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
4b3c2c2ee09bf07f5748baf5c67d19b7
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } StringTokenizer str = null; BufferedReader in; PrintWriter out; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); out.close(); } String nextString() throws IOException { return in.readLine(); } String nextToken() throws IOException { if (str == null || !str.hasMoreElements()) { str = new StringTokenizer(nextString()); } return str.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()); } class Point implements Comparable<Point> { int x; int y; @Override public int compareTo(Point p) { if (p.x > x) return -1; if (p.x < x) return 1; if (p.y > y) return -1; if (p.y < y) return 1; return 0; } } private double Rastoyanie(Point p[], int i, int l) { int xx = p[i].x - p[l].x; int yy = p[i].y - p[l].y; xx = xx * xx; yy = yy * yy; return Math.sqrt(xx + yy); } private boolean Na_odnoy_pramoy(Point p[], int i, int j, int l) { return (p[i].y - p[j].y) * p[l].x + (p[j].x - p[i].x) * p[l].y + (p[i].x * p[j].y - p[j].x * p[i].y) == 0; } int n; int a[][]; boolean f[][]; void solve() throws IOException { n = nextInt(); a = new int[n][n]; f = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextInt(); f[i][j] = false; } } int k = (n - 1) / 2; for (int i = 0; i < n; i++) { f[i][i] = true; f[n - 1 - i][i] = true; f[i][k] = true; f[k][i] = true; } int s = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (f[i][j]) s += a[i][j]; } } out.println(s); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
3a007661c1c54667fa46b2d5a2fe0880
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[][] = new int[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j]=in.nextInt(); int mid = (n-1)/2; int ans = 0; for(int i=0;i<n;i++) if(i!=mid) ans+=a[mid][i]+a[i][mid]; for(int i=0;i<n;i++){ if(i!=mid){ ans+=a[i][i]+a[i][n-i-1]; } } ans+=a[mid][mid]; System.out.print(ans); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
cddb5082871a382b1069c458ff7df631
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class ab3 { public static void debug(Object... obs) { System.out.println(Arrays.deepToString(obs)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); boolean[][]dn=new boolean[n][n]; int[][]v=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { v[i][j]=sc.nextInt(); } } long su=0; for(int i=0;i<n;i++) { if(!dn[n/2][i]) { su+=v[n/2][i]; dn[n/2][i]=true; } if(!dn[i][n/2]) { su+=v[i][n/2]; dn[i][n/2]=true; } if(!dn[i][i]) { su+=v[i][i]; dn[i][i]=true; } if(!dn[i][n-1-i]) { su+=v[i][n-1-i]; dn[i][n-1-i]=true; } } System.out.println(su); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
1bac27a7e757d85eecbfbf4e3a93ec89
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); try { int size = Integer.parseInt(br.readLine()); int rezultat = 0, middle = size/2; for(int i = 0; i < size; i++) { String[] vrstica = br.readLine().split(" "); for(int j = 0; j < size; j++) { if(j == middle) rezultat += Integer.parseInt(vrstica[j]); else if(i == middle) rezultat += Integer.parseInt(vrstica[j]); else if(i+j == size-1) rezultat += Integer.parseInt(vrstica[j]); else if(i == j) rezultat += Integer.parseInt(vrstica[j]); } } System.out.println(rezultat); } catch(Exception ex) { System.out.println("Something went wrong!"); } } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
139f7c3217e6627b8b92c0a8ba289759
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static void init() { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); } static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { System.out.println(e); System.exit(1); } return tokenizer.nextToken(); } static byte nextByte() { return Byte.parseByte(nextToken()); } static short nextShort() { return Short.parseShort(nextToken()); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static float nextFloat() { return Float.parseFloat(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static void solve() { int n = nextInt(); byte[][] arr = new byte[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) arr[i][j] = nextByte(); int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i][i]; arr[i][i] = 0; sum += arr[i][n - i - 1]; arr[i][n - i - 1] = 0; sum += arr[i][n / 2]; arr[i][n / 2] = 0; sum += arr[n / 2][i]; arr[n / 2][i] = 0; } writer.println(sum); } static void close() { try { reader.close(); writer.flush(); writer.close(); } catch (IOException e) { System.out.println(e); System.exit(1); } } public static void main(String[] args) { init(); solve(); close(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
6c8f7f15cd61d291da2b5e42d0238b77
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class ABBYY_Cup_2012_Div2_A implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok; public static void main(String[] args) { new Thread(null, new ABBYY_Cup_2012_Div2_A(), "", 256 * (1L << 20)).start(); } @Override public void run() { try { long startTime = System.currentTimeMillis(); if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); tok = new StringTokenizer(""); solve(); in.close(); out.close(); long freeMemory = Runtime.getRuntime().freeMemory(); long totalMemory = Runtime.getRuntime().totalMemory(); long endTime = System.currentTimeMillis(); System.err.println("Time = " + (endTime - startTime)); System.err.println("Memory = " + ((totalMemory - freeMemory) >> 10)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } void debug(Object... o) { if (!ONLINE_JUDGE) { System.err.println(Arrays.deepToString(o)); } } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution void solve() throws IOException { int n = readInt(); int[][] a = new int[n][n]; long sum = 0; for (int i = 0; i < n; i++) { for (int j =0 ; j < n; j++) { a[i][j] = readInt(); if (good(i,j,n)) sum += a[i][j]; } } out.println(sum); } private boolean good(int i, int j, int n) { if (i == n/2) return true; if (j == n/2) return true; if (i == j) return true; if (i == n-j-1) return true; return false; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
bb0ea277fadb7a48766767345492d69c
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.InputMismatchException; /** * Created with IntelliJ IDEA. * User: DOAN Minh Quy * Date: 7/29/13 * Time: 7:13 PM */ public class Task177A { public static void main(String[] args) { new Task177A().run(); } void run() { Task177AReader reader = new Task177AReader(System.in); Task177AWriter writer = new Task177AWriter(System.out); int n = reader.nextInt(); int[][] matrix = new int[n][n]; for(int i = 0 ; i < n ; ++i){ for(int j = 0 ; j < n ; ++j){ matrix[i][j] = reader.nextInt(); } } int sum = 0; for(int i = 0 ; i < n ; ++i){ sum += matrix[i][i] + matrix[i][n-1-i] + matrix[n/2][i] + matrix[i][n/2]; } sum -= 3 * matrix[n/2][n/2]; writer.println(sum); writer.close(); } } class Task177AReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public Task177AReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } class Task177AWriter { private final PrintWriter writer; public Task177AWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
858f08f7d7517a1cb2cec75f4b1de3c9
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class Main { public void solve( ) throws Throwable { int n = in.nextInt( ), sum = 0; //int mat[ ][ ] = new int[ n ][ n ]; //boolean vis[ ][ ] = new boolean[ n ][ n ]; for ( int i = 0; i < n; ++i ) { for ( int j = 0; j < n; ++j ) { int cur = in.nextInt( ); if ( i == j || i + j == n - 1 || i == n / 2 || j == n / 2 ) { sum += cur; } else { //debug( i, j ); } } } out.println( sum ); } public void run( ) { in = new FastScanner( System.in ); out = new PrintWriter( new PrintStream( System.out ), true ); try { solve( ); out.close( ); System.exit( 0 ); } catch( Throwable e ) { e.printStackTrace( ); System.exit( -1 ); } } public void debug( Object...os ) { System.err.println( Arrays.deepToString( os ) ); } public static void main( String[ ] args ) { ( new Main( ) ).run( ); } private FastScanner in; private PrintWriter out; private static class FastScanner { private int charsRead; private int currentRead; private byte buffer[ ] = new byte[ 0x1000 ]; private InputStream reader; public FastScanner( InputStream in ) { reader = in; } public int read( ) { if ( charsRead == -1 ) { throw new InputMismatchException( ); } if ( currentRead >= charsRead ) { currentRead = 0; try { charsRead = reader.read( buffer ); } catch( IOException e ) { throw new InputMismatchException( ); } if ( charsRead <= 0 ) { return -1; } } return buffer[ currentRead++ ]; } public int nextInt( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( sign == -1 ) { c = read( ); } if ( c == -1 || !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int ans = 0; while ( !isWhitespace( c ) && c != -1 ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10 + num; c = read( ); } return ans * sign; } public long nextLong( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( sign == -1 ) { c = read( ); } if ( c == -1 || !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } long ans = 0; while ( !isWhitespace( c ) && c != -1 ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10 + num; c = read( ); } return ans * sign; } public boolean isWhitespace( int c ) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1; } public String next( ) { int c = read( ); StringBuffer ans = new StringBuffer( ); while ( isWhitespace( c ) && c != -1 ) { c = read( ); } if ( c == -1 ) { return null; } while ( !isWhitespace( c ) && c != -1 ) { ans.appendCodePoint( c ); c = read( ); } return ans.toString( ); } public String nextLine( ) { String ans = nextLine0( ); while ( ans.trim( ).length( ) == 0 ) { ans = nextLine0( ); } return ans; } private String nextLine0( ) { int c = read( ); if ( c == -1 ) { return null; } StringBuffer ans = new StringBuffer( ); while ( c != '\n' && c != '\r' && c != -1 ) { ans.appendCodePoint( c ); c = read( ); } return ans.toString( ); } public double nextDouble( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '.' && c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( c == '-' ) { c = read( ); } double ans = 0; while ( c != -1 && c != '.' && !isWhitespace( c ) ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10.0 + num; c = read( ); } if ( !isWhitespace( c ) && c != -1 && c != '.' ) { throw new InputMismatchException( ); } double pow10 = 1.0; if ( c == '.' ) { c = read( ); } while ( !isWhitespace( c ) && c != -1 ) { pow10 *= 10.0; if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10.0 + num; c = read( ); } return ans * sign / pow10; } } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
acae3182375f83a9857786c622ccfb53
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class ABBY_easy_A1 { static int sum; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = sc.nextInt(); if(i==j){ sum+=a[i][j]; } if(i==n-j-1){ sum+=a[i][j]; // System.out.println("["+i+","+j+"] "); } if(i==(n/2)){ sum+=a[i][j]; } if(j==(n/2)){ sum+=a[i][j]; } } } sum = sum - 3*a[n/2][n/2]; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are: 1 ≤ n ≤ 5 The input limitations for getting 100 points are: 1 ≤ n ≤ 101
800
Print a single integer — the sum of good matrix elements.
standard output
PASSED
08a4a4284f38ba324bf034b155f613d2
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.*; import java.util.*; public class C811 { public static void main(String[] args) throws IOException { IO io = new IO(System.in); int[] dp = new int[5050]; int[] a = new int[101101]; boolean[] used = new boolean[5050]; int[] firstPos = new int[5050]; int[] lastPos = new int[5050]; int n = io.nextInt(); for (int i = 0; i < n; i++) { a[i + 1] = io.nextInt(); if (firstPos[a[i + 1]] == 0) { firstPos[a[i + 1]] = i + 1; } lastPos[a[i+1]] = i + 1; } for (int i = 1; i <= n; i++) { int res = dp[i - 1]; int t = 0; Arrays.fill(used, false); int to = i; for (int j = i; j > 0; --j) { int x = a[j]; if (lastPos[x] > i) { break; } to = Math.min(to, firstPos[x]); if (!used[x]) { used[x] = true; t ^= x; } if (to == j) { res = Math.max(res, dp[j - 1] + t); } } dp[i] = res; } io.println(dp[n]); io.close(); } static class IO extends PrintWriter { static BufferedReader r; static StringTokenizer t; public IO(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); t = new StringTokenizer(""); } public String next() throws IOException { while (!t.hasMoreTokens()) { t = new StringTokenizer(r.readLine()); } return t.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
66e2194fe076b1d731e55e7d9fe7ce65
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; class Pair { int u, v; Pair(int x, int y) { u = x; v = y; } } void solve() { int n = ni(); int arr[] = new int[n]; HashMap<Integer, Pair> map = new HashMap<Integer, Pair>(); for (int i = 0; i < n; i++) { arr[i] = ni(); if (!map.containsKey(arr[i])) map.put(arr[i], new Pair(i, i)); else { Pair p = map.get(arr[i]); p.v = i; } } long ans[] = new long[n + 3]; HashSet<Integer> us = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (i != 0) ans[i] = Math.max(ans[i - 1], ans[i]); if (us.contains(arr[i])) continue; us.add(arr[i]); TreeSet<Integer> set = new TreeSet<Integer>(); Pair p = map.get(arr[i]); set.add(arr[i]); int l = i, r = i; int lm = p.u, rm = p.v; while (!((lm == l+1||l<0) && (rm == r-1||r>=n))) { int km = lm, kr = rm; while (l != km - 1 && l >= 0) { lm = Math.min(lm, map.get(arr[l]).u); rm = Math.max(rm, map.get(arr[l]).v); set.add(arr[l]); l--; } while (r != kr + 1 && r < n) { lm = Math.min(lm, map.get(arr[r]).u); rm = Math.max(rm, map.get(arr[r]).v); set.add(arr[r]); r++; } } r--; long temp = 0; while (!set.isEmpty()) temp ^= set.pollFirst(); ans[r] = Math.max(ans[r], temp + (l >= 0 ? ans[l] : 0)); } out.println(ans[n-1]); } void soln() { is = System.in; out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new CODEFORCES().soln(); } // To Get Input // Some Buffer Methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
da341be60a61ece0d5b6b569b15cd07e
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
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 n; static int[] a; static int[] first = new int[5003]; static int[] last = new int[5003]; static boolean[] ap = new boolean[5003]; static int[] memo; public static void main(String[] args) { n = in.nextInt(); a = new int[n]; memo = new int[n]; Arrays.fill(first, -1); Arrays.fill(last, -1); Arrays.fill(memo, -1); for(int i=0; i<n; ++i) { a[i] = in.nextInt(); if(!ap[a[i]]) { first[a[i]] = i; ap[a[i]] = true; } last[a[i]] = i; } System.out.println( maxC(0) ); out.close(); } static int maxC(int i) { if(i == n) return 0; if(memo[i] != -1) return memo[i]; if(first[a[i]] != i) { return memo[i] = maxC(i+1); } int from = i; int to = last[a[i]]; int pc = 0; for(int j = from; j <= to; ++j) { if(first[a[j]] < from) return memo[i] = maxC(i+1); if(first[a[j]] == j) { to = Math.max(to, last[a[j]]); pc ^= a[j]; } } int ret = Math.max(maxC(i+1), pc + maxC(to + 1)); return memo[i] = ret; } } 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
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
f1590818d89bf6b7b3d6ab37c97098cb
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.*; import java.util.*; public class c { public static void main(String[] args){ Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n=sc.nextInt(); int[] a=new int[n+1]; int[] ppl=new int[5001]; for(int i=1; i<=n; i++){ a[i]=sc.nextInt(); ppl[a[i]]++; } int[] dp=new int[n+1]; for(int i=1; i<=n; i++){ int sum=0, res=0; boolean[] visited=new boolean[5001]; for(int j=i; j>0; j--){ if(!visited[a[j]]){ sum+=ppl[a[j]]; res^=a[j]; visited[a[j]]=true; } sum--; dp[i]=Math.max(dp[i], dp[j-1]+(sum>0?0:res)); } } System.out.println(dp[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
1b7dfcda316c4964db01d3a921c73339
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D2416C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] C = new int[5010]; int[] arr = new int[n]; s.nextLine(); for(int i = 0; i < n; i++){ arr[i] = s.nextInt(); C[arr[i]]++; } int[]d = new int[n+1]; for(int i = 0; i < n; i++){ d[i+1] = d[i]; int bad=0, x = 0; int[] temp = new int[5010]; for(int j = i; j >= 0; j--){ temp[arr[j]]++; if(temp[arr[j]]==1){ bad++; x=x^arr[j]; } if(temp[arr[j]]==C[arr[j]])bad--; if(bad == 0){ d[i+1] = Math.max(d[i+1],x+d[j]); } } } System.out.println(d[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
569879cc57a5942cc47f7da8e81911ab
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class Main3 { static long mod = 1000000007L; public static void main(String[] args) { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int[] a = scanner.nextIntArray(n); int[] min = new int[5010]; int[] max = new int[5010]; Arrays.fill(min, 6000); for (int i = 0; i < n; i++) { min[a[i]] = Math.min(i, min[a[i]]); max[a[i]] = Math.max(i, max[a[i]]); } List<Segment> segments = new ArrayList<>(); boolean[] allUsed = new boolean[5010]; int all = 0; for (int i = 0; i < n; i++) { if (!allUsed[a[i]]) { all = all ^ a[i]; allUsed[a[i]] = true; } } segments.add(new Segment(0, n -1, all)); a: for (int i = 0; i < 5010; i++) { if (min[i] > max[i]) continue a; int maxG = max[i]; int res = 0; boolean[] used = new boolean[5010]; for (int k = min[i]; k <= maxG; k++) { if (min[a[k]] < min[i]) continue a; maxG = Math.max(maxG, max[a[k]]); if (!used[a[k]]) { res = res ^ a[k]; used[a[k]] = true; } } segments.add(new Segment(min[i], maxG, res)); } Collections.sort(segments); Segment root = segments.get(0); for (Segment seg : segments) { root.add(seg); } System.out.println(root.bestScore()); } static class Segment implements Comparable<Segment> { int start, end, score; List<Segment> childs = new ArrayList<>(); public Segment(int start, int end, int score) { this.start = start; this.end = end; this.score = score; } @Override public int compareTo(Segment o) { return -Integer.compare(end - start, o.end - o.start); } boolean add(Segment another) { if (another.start == start && another.end == end && another.score == score) return true; if (another.start >= start && another.end <= end) { for (Segment ch : childs) { if (ch.add(another)) return true; } childs.add(another); return true; } else { return false; } } int bestScore() { if (childs.isEmpty()) return score; return Math.max(score, childs.stream().mapToInt(Segment::bestScore).sum()); } } 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 sum"); 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 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 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; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
b1e84af0f203e91941782a3a9d1d666d
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Third { static int n; static int[] arr; static int[] last; static int[] first; static Integer[] dp; public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); arr = new int[n]; last = new int[6001]; first = new int[6001]; for(int i=0; i<n; i++) { arr[i] = in.nextInt(); last[arr[i]] = i; if(first[arr[i]] == 0) { first[arr[i]] = i; } } first[arr[0]] = 0; dp = new Integer[n]; System.out.println(rec(0)); } private static int rec(int i) { if(i == n) { return 0; } else if(dp[i] != null) { return dp[i]; } else { int ans = rec(i+1); int need = -1; Set<Integer> set = new HashSet<>(); int cur = 0; for(int j=i; j<n; j++) { if(!set.contains(arr[j])) { if(first[arr[j]] != j) { break; } set.add(arr[j]); cur ^= arr[j]; } need = Math.max(need, last[arr[j]]); if(j >= need) { ans = Math.max(ans, cur + rec(j+1)); } } return dp[i] = ans; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
69777d209609c2c6ad5f2373193c5cda
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Cl { static int[][] memo, x; static int[] min, max, a; static int n; static int max(int idx, int stpnt) { if (idx == n) return stpnt < n ? x[stpnt][n - 1] : 0; if (memo[idx][stpnt] != -1) return memo[idx][stpnt]; int ans = 0; if (min[a[idx]] == idx) ans = (idx > 0 ? x[stpnt][idx - 1] : 0) + max(max[a[idx]] + 1, idx); if (min[a[idx]] >= stpnt) ans = Math.max(ans, max(max[a[idx]] + 1, stpnt)); ans = Math.max(ans, (idx > 0 ? x[stpnt][idx - 1] : 0) + max(idx + 1, idx + 1)); return memo[idx][stpnt] = ans; } public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = bf.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = bf.nextInt(); } int inf = 5001; x = new int[n][n]; memo = new int[inf][inf]; min = new int[inf]; max = new int[inf]; for (int[] i : memo) Arrays.fill(i, -1); Arrays.fill(min, inf); boolean[] b = new boolean[inf]; int xor = 0; for (int i = 0; i < x.length; i++) { Arrays.fill(b, false); xor = a[i]; b[a[i]] = true; if (min[a[i]] == inf) min[a[i]] = i; max[a[i]] = i; for (int j = i; j < x.length; j++) { if (!b[a[j]]) { b[a[j]] = true; xor ^= a[j]; } x[i][j] = xor; } } for (int i = 0; i < min.length; i++) { for (int j = min[i] + 1; j < max[i]; j++) { min[i] = Math.min(min[i], min[a[j]]); max[i] = Math.max(max[i], max[a[j]]); } } out.println(max(0, 0)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
d02715b5db51f057df254e8c069aa6cb
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class CF811C { static class Node { int l; int r; int val; } static int[] dp; static HashMap<Integer,Node> hm; public static void main(String[] args) { FastReader fr = new FastReader(); int n = fr.nextInt(); int[] arr = new int[n]; dp = new int[n]; hm = new HashMap<Integer,Node>(); //Put in HashMap and take the left and right indexes. for(int i=0;i<n;i++) { arr[i] = fr.nextInt(); if(hm.containsKey(arr[i])) { hm.get(arr[i]).r = i; } else { Node t = new Node(); t.l = i; t.r = i; hm.put(arr[i], t); } } //Calculate the proper indexes by accounting all the values inside given subarray Iterator<Entry<Integer,Node>> it = hm.entrySet().iterator(); while(it.hasNext()) { Map.Entry<Integer,Node> pair = (Map.Entry<Integer,Node>)it.next(); Node curNode = pair.getValue(); int cur_l = curNode.l; int cur_r = curNode.r; for(int j=cur_l;j<=cur_r;j++) { Node in_btw_node = hm.get(arr[j]); //cur_l = Math.min(cur_l, in_btw_node.l); if(cur_l>in_btw_node.l) { cur_l = in_btw_node.l; j = cur_l; } if(cur_r<in_btw_node.r) { cur_r = in_btw_node.r; curNode.r = cur_r; } //cur_r = Math.max(cur_r, in_btw_node.r); } curNode.l = cur_l; curNode.r = cur_r; } //Calculate the Max XOR Value for every item in the Hm Iterator<Entry<Integer,Node>> it1 = hm.entrySet().iterator(); while(it1.hasNext()) { Map.Entry<Integer,Node> pair = (Map.Entry<Integer,Node>)it1.next(); Node curNode = pair.getValue(); HashSet<Integer> hs = new HashSet<Integer>(); int val = 0; //hs.add(val); for(int j=curNode.l;j<=curNode.r;j++) { //System.out.println("-)----"+arr[j]); if(!hs.contains(arr[j])) { //System.out.println(val+"-----"+arr[j]); val = val^arr[j]; hs.add(arr[j]); //System.out.println(val+"-----"); } } curNode.val = val; //System.out.println(pair.getKey()+" "+curNode.val+" "+curNode.l+" "+curNode.r+" "); } //Calculate the Max by using DP. for(int i=0;i<n;i++) { //if(hm.get(arr[i]).r>i) // dp[i] = 0; //else dp[i] = hm.get(arr[i]).val; //dp[i] = arr[i]; int cur_val = dp[i]; for(int j=0;j<i;j++) { //Check if this can be taken if(hm.get(arr[j]).r<hm.get(arr[i]).l) { dp[i] = Math.max(dp[i], dp[j]+cur_val); } } } int ans = Integer.MIN_VALUE; //for(int i=0;i<n;i++) // System.out.print(dp[i]+" "); for(int i=0;i<n;i++) ans = Math.max(ans,dp[i]); System.out.println(ans); } //Better IO Class static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public Float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { System.out.println(e); } return str; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
d825b172309a24bf56410d9a7b88a444
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class letsgooo implements Runnable { public static void main(String[] args) { // TODO Auto-generated method stub new Thread(null, new letsgooo(), ":)", 1 << 28).start(); } static int mod = (int) 1e9 + 7; static Integer[] dp; static HashMap<Integer,Integer> leftmost; static HashMap<Integer,Integer> rightmost; static int[] p; @Override public void run() { // TODO Auto-generated method stub try { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); dp = new Integer[n]; Arrays.fill(dp, -1); p = new int[n]; leftmost = new HashMap<Integer,Integer>(); rightmost = new HashMap<Integer,Integer>(); for(int i = 0; i < n; i++){ p[i]=in.nextInt(); if(!leftmost.containsKey(p[i])){ leftmost.put(p[i], i); } rightmost.put(p[i], i); } System.out.println(go(0)); out.close(); } catch (Exception e) { throw e; } } private static int go(int idx){ if(idx>=dp.length)return 0; if(dp[idx]!=-1)return dp[idx]; //leave int best = go(idx+1); //take boolean valid = true; int l = idx; int r = idx; int cur = 0; HashSet<Integer> seen = new HashSet<Integer>(); for(int j = l; valid&&j <= r; j++){ if(idx>leftmost.get(p[j])){ valid=false; break; } if(!seen.contains(p[j])){ cur^=p[j]; } seen.add(p[j]); r=Math.max(r, rightmost.get(p[j])); } if(valid){ best=Math.max(best, cur+go(r+1)); } return dp[idx]=best; } private static boolean isPalindrome(String s) { for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false; } return true; } private static int[] cxor(int[] given) { int[] ans = new int[given.length + 1]; for (int i = 1; i < ans.length; i++) { ans[i] = given[i - 1] ^ ans[i - 1]; } return ans; } private static int circularqueryxor(int[] cxor, int x1, int x2) { // no rotate needed if (x2 < cxor.length) return querycxor(cxor, x1, x2); int ans = 0; // 1 to end ans = querycxor(cxor, x1 % (cxor.length - 1), cxor.length - 1); x1 += cxor.length - 1 - (x1 % (cxor.length - 1)); int diff = x2 - x1; int iterations = diff / (cxor.length - 1); // wraparound if (iterations % 2 == 1) { ans ^= querycxor(cxor, 0, cxor.length - 1); } // start to 2 ans ^= querycxor(cxor, 0, x2 % (cxor.length - 1)); return ans; } private static int querycxor(int[] cxor, int x1, int x2) { return cxor[x2] ^ cxor[x1]; } private static double[][][] csum(double[][][] given) { double[][][] ans = new double[given.length + 1][given[0].length + 1][given[0][0].length + 1]; for (int i = 1; i < ans.length; i++) { for (int j = 1; j < ans[i].length; j++) { for (int k = 1; k < ans[i][j].length; k++) { ans[i][j][k] = given[i - 1][j - 1][k - 1] + ans[i - 1][j][k] + ans[i][j - 1][k] + ans[i][j][k - 1] - ans[i][j - 1][k - 1] - ans[i - 1][j][k - 1] - ans[i - 1][j - 1][k] + ans[i - 1][j - 1][k - 1]; // System.out.println(i+" "+j+" "+k+" "+ans[i][j][k]+" // "+given[i-1][j-1][k-1]); } } } return ans; } private static double querycsum(double[][][] csum, int x1, int y1, int z1, int x2, int y2, int z2) { if (x1 > x2 || y1 > y2 || z1 > z2) return 0; if (x1 < 0) x1 = 0; if (y1 < 0) y1 = 0; if (z1 < 0) z1 = 0; if (x2 < 0) x2 = 0; if (y2 < 0) y2 = 0; if (z2 < 0) z2 = 0; if (x1 >= csum.length) x1 = csum.length - 1; if (y1 >= csum[0].length) y1 = csum[0].length - 1; if (z1 >= csum[0][0].length) z1 = csum[0][0].length - 1; if (x2 >= csum.length) x2 = csum.length - 1; if (y2 >= csum[0].length) y2 = csum[0].length - 1; if (z2 >= csum[0][0].length) z2 = csum[0][0].length - 1; double inclusion = csum[x2][y2][z2]; double exclusion = csum[x1][y2][z2] + csum[x2][y1][z2] + csum[x2][y2][z1]; double innerinclusion = csum[x2][y1][z1] + csum[x1][y2][z1] + csum[x1][y1][z2]; double innerexclusion = csum[x1][y1][z1]; // System.out.println("("+x1+", "+y1+", "+z1+") -> ("+(x2-1)+", // "+(y2-1)+", "+(z2-1)+") = "+(inclusion - exclusion + innerinclusion - // innerexclusion)); // System.out.println(inclusion+" "+exclusion+" "+innerinclusion+" // "+innerexclusion); return (inclusion - exclusion + innerinclusion - innerexclusion); } private static class DFA { ArrayList<DFANode> nodes; ArrayList<DFANode> start; ArrayList<DFANode> end; int alpha; DFA(int count, int alpha, int s, int e) { nodes = new ArrayList<DFANode>(); this.alpha = alpha; for (int i = 0; i < count; i++) { nodes.add(new DFANode()); nodes.get(nodes.size() - 1).idx = nodes.size() - 1; } start = new ArrayList<DFANode>(); start.add(nodes.get(s)); end = new ArrayList<DFANode>(); end.add(nodes.get(e)); } public void AddEdge(int s, int f, int letter) { nodes.get(s).transition[letter] = nodes.get(f); } public void Trim() { HashSet<DFANode> valid = new HashSet<DFANode>(); valid.addAll(nodes); for (DFANode n : nodes) { for (int i = 0; i < n.transition.length; i++) { if (!valid.contains(n.transition[i])) n.transition[i] = null; } } } private class DFANode implements Comparable<DFANode> { DFANode[] transition; int idx; public DFANode() { transition = new DFANode[alpha]; } @Override public int hashCode() { return idx; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(idx + ": <"); for (int i = 0; i < transition.length; i++) { if (transition[i] != null) { sb.append(i + ":" + transition[i].idx + ","); } } sb.append(">"); return sb.toString(); } @Override public boolean equals(Object obj) { return ((DFANode) obj).toString().equals(toString()); } @Override public int compareTo(DFANode arg0) { // TODO Auto-generated method stub return Integer.compare(idx, arg0.idx); } } private void removeUnreachable() { HashSet<DFANode> reached = new HashSet<DFANode>(); ArrayDeque<DFANode> dq = new ArrayDeque<DFANode>(); dq.addAll(start); reached.addAll(start); while (!dq.isEmpty()) { DFANode cur = dq.poll(); for (DFANode next : cur.transition) { if (next == null) continue; if (!reached.contains(next)) { dq.add(next); reached.add(next); } } } ArrayList<DFANode> dupe = new ArrayList<DFANode>(); ArrayList<DFANode> dupend = new ArrayList<DFANode>(); ArrayList<DFANode> dupstart = new ArrayList<DFANode>(); for (DFANode d : nodes) { if (reached.contains(d)) { dupe.add(d); } } for (DFANode d : end) { if (reached.contains(d)) { dupend.add(d); } } for (DFANode d : start) { if (reached.contains(d)) { dupstart.add(d); } } nodes = dupe; end = dupend; start = dupstart; } private void removeUnproductive() { HashSet<DFANode> reached = new HashSet<DFANode>(); reached.addAll(end); boolean news = false; do { news = false; for (DFANode n : nodes) { if (reached.contains(n)) continue; for (DFANode nn : n.transition) { if (nn == null) continue; if (reached.contains(nn)) { news = true; reached.add(n); } } } } while (news); ArrayList<DFANode> dupe = new ArrayList<DFANode>(); ArrayList<DFANode> dupend = new ArrayList<DFANode>(); ArrayList<DFANode> dupstart = new ArrayList<DFANode>(); for (DFANode d : nodes) { if (reached.contains(d)) { dupe.add(d); } } for (DFANode d : end) { if (reached.contains(d)) { dupend.add(d); } } for (DFANode d : start) { if (reached.contains(d)) { dupstart.add(d); } } nodes = dupe; end = dupend; start = dupstart; } private void minimize() { number(); Collections.sort(nodes); boolean[][] distinct = new boolean[nodes.size()][nodes.size()]; for (int i = 0; i < nodes.size(); i++) { for (int j = i + 1; j < nodes.size(); j++) { boolean hasi = false; boolean hasj = false; for (DFANode n : end) { if (nodes.get(i).equals(n)) hasi = true; if (nodes.get(j).equals(n)) hasj = true; } if (hasi != hasj) { distinct[i][j] = true; distinct[j][i] = true; } } } boolean news = false; do { news = false; for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { if (!distinct[i][j]) { for (int a = 0; a < nodes.get(i).transition.length; a++) { DFANode alpha = nodes.get(i).transition[a]; DFANode beta = nodes.get(j).transition[a]; if (alpha != beta) { if (alpha == null || beta == null || distinct[alpha.idx][beta.idx]) { distinct[i][j] = true; distinct[j][i] = true; news = true; } } } } } } } while (news); ArrayList<DFANode> cop = new ArrayList<DFANode>(); cop.addAll(nodes); for (int i = 0; i < distinct.length; i++) { ArrayList<DFANode> needed = new ArrayList<DFANode>(); needed.add(cop.get(i)); for (int j = i + 1; j < distinct.length; j++) { if (!distinct[i][j]) { needed.add(cop.get(j)); } } if (needed.size() > 1) { merge(needed); } } number(); } public String toString() { return start.toString() + " " + end.toString() + " " + nodes.toString(); } public void number() { removeUnreachable(); removeUnproductive(); Trim(); int num = 0; HashSet<DFANode> reached = new HashSet<DFANode>(); ArrayDeque<DFANode> dq = new ArrayDeque<DFANode>(); dq.addAll(start); reached.addAll(start); HashMap<Integer, DFANode> remap = new HashMap<Integer, DFANode>(); while (!dq.isEmpty()) { DFANode cur = dq.poll(); remap.put(num++, cur); for (DFANode next : cur.transition) { if (next == null) continue; if (!reached.contains(next)) { dq.add(next); reached.add(next); } } } for (Integer i : remap.keySet()) { remap.get(i).idx = i; } Collections.sort(nodes); } public void merge(ArrayList<DFANode> toMerge) { HashSet<DFANode> list = new HashSet<DFANode>(); DFANode twopointoh = toMerge.get(0); list.addAll(toMerge); nodes.removeAll(list); nodes.add(twopointoh); if (start.removeAll(toMerge)) { start.add(twopointoh); } if (end.removeAll(toMerge)) { end.add(twopointoh); } for (DFANode n : nodes) { for (int i = 0; i < n.transition.length; i++) { if (list.contains(n.transition[i])) { n.transition[i] = twopointoh; } } } } public boolean equals(Object o) { return ((DFA) o).toString().equals(toString()); } } private static class RMQ2D { int[][][][] rmq; int[][] data; public RMQ2D(int[][] data) { this.data = data; int k1 = Integer.numberOfTrailingZeros(Integer.highestOneBit(data.length)) + 3; int k2 = Integer.numberOfTrailingZeros(Integer.highestOneBit(data[0].length)) + 3; rmq = new int[k1][k2][data.length][data[0].length]; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[0].length; j++) { rmq[0][0][i][j] = data[i][j]; } } for (int i = 0; i < k1; i++) { for (int j = 0; j < k2; j++) { if (i == 0 && j == 0) continue; for (int x = 0; x + (1 << i) - 1 < data.length; x++) { for (int y = 0; y + (1 << j) - 1 < data[0].length; y++) { if (j == 0) { rmq[i][j][x][y] = Math.min(rmq[i - 1][j][x][y], rmq[i - 1][j][x + (1 << (i - 1))][y]); } else { rmq[i][j][x][y] = Math.min(rmq[i][j - 1][x][y], rmq[i][j - 1][x][y + (1 << (j - 1))]); } } } } } } public int query(int x1, int y1, int x2, int y2) { int i = (int) (Math.log(x2 - x1 + 1) / Math.log(2)); int j = (int) (Math.log(y2 - y1 + 1) / Math.log(2)); int min = Integer.MAX_VALUE; min = Math.min(min, rmq[i][j][x1][y1]); min = Math.min(min, rmq[i][j][x2 - (1 << i) + 1][y1]); min = Math.min(min, rmq[i][j][x1][y2 - (1 << j) + 1]); min = Math.min(min, rmq[i][j][x2 - (1 << i) + 1][y2 - (1 << j) + 1]); return min; } } private static void printArray(int[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } private static Point2D.Double reflectPoint(Point2D.Double p, Line2D.Double line) { double dY = line.y2 - line.y1, dX = line.x2 - line.x1; Point2D.Double mid = cramer(line, new Line2D.Double(p, new Point2D.Double(p.x - dY, p.y + dX))); return new Point2D.Double(2 * mid.x - p.x, 2 * mid.y - p.y); } private static double angle(Line2D.Double a, Line2D.Double b) { return ((Math.atan2(a.y1 - a.y2, a.x1 - a.x2) - Math.atan2(b.y1 - b.y2, b.x1 - b.x2)) % Math.PI + Math.PI) % Math.PI; } private static Point2D.Double cramer(Line2D.Double p, Line2D.Double q) { // solves intersection of two line segs. // must check that segs ACUTUALLY intersect beforehand double dX1 = p.x2 - p.x1, dX2 = q.x2 - q.x1; double dY1 = p.y2 - p.y1, dY2 = q.y2 - q.y1; double a1 = -dY1, b1 = dX1, c1 = dX1 * p.y1 - dY1 * p.x1; double a2 = -dY2, b2 = dX2, c2 = dX2 * q.y1 - dY2 * q.x1; double D = a1 * b2 - a2 * b1; double Dx = c1 * b2 - c2 * b1; double Dy = a1 * c2 - a2 * c1; return new Point2D.Double(Dx / D, Dy / D); } // SegTree RMQ + Range Update private static class ST { int[] list, st; int K; public ST(int[] list) { this.list = list; K = (int) Math.ceil(Math.log(list.length) / Math.log(2.0)); st = new int[list.length * 4]; build(0, (1 << K) - 1, 1); } private int build(int L, int R, int idx) { if (L == R) { if (L >= list.length) return -1; return st[idx] = L; } int mid = L + R >> 1; int l = build(L, mid, idx << 1); int r = build(mid + 1, R, (idx << 1) + 1); if (l != -1 && r != -1) return st[idx] = (list[l] <= list[r]) ? l : r;// changesign >= // max <= min if (l != -1) return st[idx] = l; if (r != -1) return st[idx] = r; return st[idx] = -1; } public int query(int L, int R) { return query(L, R, 0, (1 << K) - 1, 1); } private int query(int L, int R, int tL, int tR, int idx) { if (tL >= L && tR <= R) return st[idx]; if (tL < L && tR < L || tL > R && tR > R) return -1; int mid = tL + tR >> 1; int l = query(L, R, tL, mid, idx << 1); int r = query(L, R, mid + 1, tR, (idx << 1) + 1); if (l != -1 && r != -1) return (list[l] <= list[r]) ? l : r;// changesign if (l != -1) return l; if (r != -1) return r; return -1; } public int update(int U, int V) { return update(U, 0, (1 << K) - 1, 1, V); } private int update(int U, int tL, int tR, int idx, int V) { if (U == tL && tL == tR) { list[U] = V; return st[idx] = U; } if (tL < U && tR < U || tL > U && tR > U) return st[idx]; int mid = tL + tR >> 1; int l = update(U, tL, mid, idx << 1, V); int r = update(U, mid + 1, tR, (idx << 1) + 1, V); if (l != -1 && r != -1) return st[idx] = (list[l] <= list[r]) ? l : r;// changesign if (l != -1) return st[idx] = l; if (r != -1) return st[idx] = r; return -1; } } private static class DijkstraEdge implements Comparable<DijkstraEdge> { int length; int cost; int source; int destination; public DijkstraEdge(int from, int to, int length, int cost) { source = from; destination = to; this.length = length; this.cost = cost; } @Override public int compareTo(DijkstraEdge arg0) { // TODO Auto-generated method stub return Integer.compare(length, arg0.length); } } private static class Event implements Comparable<Event> { int x; int y; int priority; public Event(int time, int val, int priority) { this.x = time; this.y = val; this.priority = priority; } @Override public int compareTo(Event o) { // TODO Auto-generated method stub if (x != o.x) return Integer.compare(x, o.x); if (y != o.y) return Integer.compare(y, o.y); return Integer.compare(priority, o.priority); } public boolean equals(Object o) { return compareTo((Event) o) == 0; } public String toString() { return "(" + x + " , " + y + ", " + priority + ")"; } } private static class Lowlink { int N, time; int[] ord, low; boolean[] art; ArrayList<Edge>[] adj; public Lowlink(ArrayList<Edge>[] adj) { this.adj = adj; N = adj.length; } public void start() { ord = new int[N]; low = new int[N]; art = new boolean[N]; Arrays.fill(ord, -1); for (int i = 0; i < N; i++) if (ord[i] == -1) dfs(i, -1); } private int dfs(int u, int parEdge) { ord[u] = low[u] = time++; int children = 0; for (Edge e : adj[u]) { int v = e.op(u); if (e.id == parEdge) continue; if (ord[v] == -1) { low[u] = Math.min(low[u], dfs(v, e.id)); if (++children > 1 && parEdge == -1) art[u] = true; if (parEdge != -1 && low[v] >= ord[u]) art[u] = true; if (low[v] > ord[u]) e.bridge = true; } else low[u] = Math.min(low[u], ord[v]); } return low[u]; } } private static class Edge { int u, v, id; boolean bridge; public Edge(int u, int v, int id) { this.u = u; this.v = v; this.id = id; } public int op(int a) { return a == u ? v : u; } } private static class pair implements Comparable<pair> { int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } public double dist(pair other) { return Math.sqrt((a - other.a) * (a - other.a) + (b - other.b) * (b - other.b)); } @Override public int compareTo(pair arg0) { // TODO Auto-generated method stub if (a != arg0.a) return Integer.compare(a, arg0.a); return Integer.compare(b, arg0.b); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; 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 (a != other.a) return false; if (b != other.b) return false; return true; } public String toString() { return "(" + a + " , " + b + ")"; } } private static class Line { double m; double b; public Line(double m, double b) { this.m = m; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(b); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(m); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Line other = (Line) obj; if (Double.doubleToLongBits(b) != Double.doubleToLongBits(other.b)) return false; if (Double.doubleToLongBits(m) != Double.doubleToLongBits(other.m)) return false; return true; } } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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; } } private static class UtilityDinic { double eps = 1e-7; ArrayList<Edge>[] nodes; ArrayList<Double> modifiers; ArrayList<Edge> actual; ArrayList<Edge> circulatingEdges; double[] demand; int[] distance; boolean[] blocked; int source; int sink; class Edge { int from; int to; double capacity; double flow; Edge reverse; public Edge(int from, int to, double capacity, double flow, Edge reverse) { this.from = from; this.to = to; this.capacity = capacity; this.flow = flow; this.reverse = reverse; } } public UtilityDinic(int nodes) { this.circulatingEdges = new ArrayList<Edge>(); this.nodes = new ArrayList[nodes]; this.actual = new ArrayList<Edge>(); this.modifiers = new ArrayList<Double>(); for (int i = 0; i < nodes; i++) { this.nodes[i] = new ArrayList<Edge>(); } demand = new double[nodes]; } public Edge addEdge(int from, int to, double capacity) { // System.out.println(from + "->" + to + " with " + capacity); Edge forward = new Edge(from, to, capacity, 0, null); Edge reverse = new Edge(to, from, 0, 0, forward); forward.reverse = reverse; nodes[from].add(forward); nodes[to].add(reverse); actual.add(forward); return forward; } public Edge addEdge(int from, int to, double capacity, double min) { Edge o = addEdge(from, to, capacity - min); demand[from] += min; demand[to] -= min; modifiers.add(min); return o; } public void addCirculatingEdges(int supersource, int supersink) { for (int i = 0; i < demand.length; i++) { if (Math.abs(demand[i]) < eps) continue; if (demand[i] < 0) { circulatingEdges.add(addEdge(supersource, i, -demand[i])); } if (demand[i] > 0) { circulatingEdges.add(addEdge(i, supersink, demand[i])); } } } public double flowX(int source, int sink, double amount) { // System.out.println("Sending "+amount+" from "+source+" to // "+sink); double flow = 0; this.source = source; this.sink = sink; while (bfs()) { blocked = new boolean[nodes.length]; double val = dfs(source, amount - flow); flow += val; if (flow >= amount) break; } if (circulatingEdges.size() > 0) { for (Edge e : circulatingEdges) { // System.out.println(e.flow+" / "+e.capacity); if (Math.abs(e.flow - e.capacity) > eps) { return -1; } else { if (e.from == source) { flow -= e.flow; } } } } return flow; } public double flow(int source, int sink) { return flowX(source, sink, Double.MAX_VALUE); } // Lexicographically first flow on a bipartite graph // Assumes all left side nodes are added first, then right side nodes, // then source and sink // Assumes matching left side with lower right side than current // matching is better lexicographically // Assumes edges are added from top to bottom per node on the left public double lexicoFlow(int source, int sink) { // generate initial flow graph double totalFlow = flow(source, sink); for (int i = 0; i < nodes.length - 2; i++) { boolean leftside = true; for (Edge e : nodes[i]) { if (e.to == sink) leftside = false; } if (!leftside) break; // System.out.println("Testing node "+i); for (Edge e : nodes[i]) { if (e.to == source || e.from == source || e.to == sink || e.from == sink) continue; // System.out.println("Testing Edge to "+e.to); if (e.flow == 0) { e.capacity = 0; e.reverse.capacity = 0; // System.out.println(e.reverse.flow); e.reverse.flow = 0; continue; } if (e.flow < 0) continue; ForceBlock(e); } } return totalFlow; } public boolean ForceBlock(Edge e) { double cur = e.flow; double cap = e.capacity; double rcur = e.reverse.flow; double rcap = e.reverse.capacity; e.capacity = 0; e.flow = 0; e.reverse.flow = 0; e.reverse.capacity = 0; double can = flowX(e.from, e.to, cur); if (Math.abs(can - cur) < 1e-7) { return true; } else { e.capacity = cap; e.flow = cur; e.reverse.capacity = rcap; e.reverse.flow = rcur; return false; } } public boolean bfs() { distance = new int[nodes.length]; Arrays.fill(distance, Integer.MAX_VALUE); distance[sink] = 0; ArrayDeque<Integer> current = new ArrayDeque<Integer>(); current.add(sink); while (!current.isEmpty()) { int cur = current.poll(); if (distance[cur] >= distance[source]) break; for (Edge e : nodes[cur]) { if ((e.reverse.capacity - e.reverse.flow) > eps) { if (distance[e.to] > (distance[cur] + 1)) { current.add(e.to); distance[e.to] = distance[cur] + 1; } } } } return distance[source] != Integer.MAX_VALUE; } public double dfs(int pos, double min) { if (pos == sink) { return min; } double flow = 0; for (Edge e : nodes[pos]) { if (blocked[e.to]) continue; if (distance[e.to] != distance[pos] - 1) continue; if ((e.capacity - e.flow) > eps) { double res = dfs(e.to, Math.min(min, e.capacity - e.flow)); flow += res; min -= res; e.flow += res; e.reverse.flow -= res; } if (min <= eps) break; } if (min > eps) { blocked[pos] = true; } return flow; } public void removeEdge(Edge e) { // actual.remove(e); nodes[e.from].remove(e); nodes[e.to].remove(e.reverse); // circulatingEdges.remove(e); } public void removeCirculatingEdges() { for (Edge e : circulatingEdges) { removeEdge(e); } circulatingEdges = new ArrayList<Edge>(); } public void addDemand(double demand, int node) { this.demand[node] += demand; } public void drain() { for (ArrayList<Edge> al : nodes) { for (Edge e : al) { e.flow = 0; } } } } private static class STmine { /** * The value we don't care about, use 987654321 for min, and 0 for bit * operations. */ int ignore = 0; /** * The index of the node representing the left subtree of the current * node. */ int[] left; /** * The index of the node representing the right subtree of the current * node. */ int[] right; /** * The value of the node represented by the index. */ int[] val; /** * The left bound of the range represented by the node at this index. */ int[] a; /** * The right bound of the range represented by the node at this index. */ int[] b; /** * The delta array, representing changes that have yet to be propogated. */ int[] prop; /** * The height of a given node. 0 = leaf. */ int[] height; /** * Initializes a new segment tree, filled with zeros. * * @param n * The size of the segment tree (zero indexed). */ STmine(int n) { left = new int[4 * n]; right = new int[4 * n]; val = new int[4 * n]; prop = new int[4 * n]; height = new int[4 * n]; a = new int[4 * n]; b = new int[4 * n]; init(0, 0, n - 1); } /** * Initializes the Segment Tree, setting up {@link STmine#a}, * {@link STmine#b}, {@link STmine#left}, {@link STmine#right}. * * @param at * The current node * @param l * The leftmost value of the range represented by this node. * @param r * The rightmost value of the range represented by this node. * @return The index of the node that was just processed. */ int init(int at, int l, int r) { a[at] = l; b[at] = r; if (l == r) { left[at] = right[at] = -1; height[at] = 0; } else { int mid = l + r >> 1; left[at] = init(2 * at + 1, l, mid); right[at] = init(2 * at + 2, mid + 1, r); height[at] = Math.max(height[left[at]], height[right[at]]) + 1; } return at++; } /** * * @param x * The left value of the range to be queried * @param y * The right value of the range to be queried * @return The minimum value between x and y. */ int get(int x, int y) { return go(x, y, 0); } /** * Lazily propogates the value of {@link STmine#prop} to the left and * right children. * * @param at * The current node. */ void push(int at) { System.out.println("PUSH " + prop[at]); if (prop[at] != 0) { go3(a[left[at]], b[left[at]], prop[at], left[at]); go3(a[right[at]], b[right[at]], prop[at], right[at]); prop[at] = 0; } } /** * * @param x * The left bound of the range to be queried * @param y * The right bound of the range to be queried * @param at * The current node * @return The minimum on the range x->y, within the domain of what is * represented by at */ int go(int x, int y, int at) { if (at == -1 || y < a[at] || x > b[at]) return ignore; if (x <= a[at] && y >= b[at]) { push(at); System.out.println(prop[at] + " " + val[at]); return val[at]; } System.out.println(x + " " + y + " " + a[at] + " " + b[at]); push(at); return eval(at, go(x, y, left[at]), go(x, y, right[at])); } /** * Add v to elements x through y * * @param x * The left index of the range to be added to. * @param y * The right index of the range to be added to. * @param v * The value to be added. */ void add(int x, int y, int v) { go3(x, y, v, 0); } void noLazySet(int x, int y, int v) { go2(x, y, v, 0); } /*** * Sets a value and then updates the tree in a non-lazy fashion * * @param x * The left value of the range being set * @param y * The right value of the range being set * @param v * The value to be set to * @param at * The current node */ void go2(int x, int y, int v, int at) { if (at == -1) return; if (y < a[at] || x > b[at]) return; x = Math.max(x, a[at]); y = Math.min(y, b[at]); if (y == b[at] && x == a[at]) { val[at] = v; return; } go2(x, y, v, left[at]); go2(x, y, v, right[at]); val[at] = eval(at, val[left[at]], val[right[at]]); } /** * Update values and push prop as far as necessary to query x->y. * * @param x * The left bound of the range to be queried. * @param y * The right bound of the range to be queried. * @param v * The current prop value being pushed from parent. * @param at * The current node. */ void go3(int x, int y, int v, int at) { if (at == -1) return; if (y < a[at] || x > b[at]) return; x = Math.max(x, a[at]); y = Math.min(y, b[at]); if (y == b[at] && x == a[at]) { val[at] += v; prop[at] += v; return; } push(at); go3(x, y, v, left[at]); go3(x, y, v, right[at]); val[at] = eval(at, val[left[at]], val[right[at]]); } /** * Changes per program, evaluates the new value for a given node given * that left and right are up to date. * * @param at * The current node. * @param lval * The value representing the left subtree * @param rval * The value representing the right subtree */ int eval(int at, int lval, int rval) { // System.out.println("("+height[at]+" "+at+") "+lval+" "+rval); System.out.println(at + " " + lval + " " + rval + "!"); return Math.min(lval, rval); } } private static class AhoCorasick { int ALPHA = 26; int nodeCount; int[][] transition; BitSet[] word; public void createAhoCorasick(String[] strs) { int maxNodes = 1; for (String s : strs) { maxNodes += s.length(); } int[][] children = new int[ALPHA][maxNodes]; word = new BitSet[maxNodes]; for (int i = 0; i < word.length; i++) word[i] = new BitSet(); nodeCount = 1; for (int i = 0; i < strs.length; i++) { String s = strs[i]; int node = 0; for (char ch : s.toCharArray()) { int c = ch - 'a'; if (children[c][node] == 0) { children[c][node] = nodeCount; nodeCount++; } node = children[c][node]; } word[node].set(i); } transition = new int[ALPHA][nodeCount]; ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); queue.add(0); queue.add(0); while (queue.size() > 0) { int node = queue.remove(); int suffLink = queue.remove(); word[node].or(word[suffLink]); for (int ch = 0; ch < ALPHA; ch++) { if (children[ch][node] != 0) { transition[ch][node] = children[ch][node]; queue.add(children[ch][node]); queue.add(node == 0 ? 0 : transition[ch][suffLink]); } else { transition[ch][node] = transition[ch][suffLink]; } } } } } private static class NEWMATH { static ArrayList<Long> primes; static Random r = new Random(); private static void factorize(long n) { primes = new ArrayList<>(); while (!BigInteger.valueOf(n).isProbablePrime(20)) { long rho = rho(n); primes.add(rho); n /= rho; } primes.add(n); } private static long rho(long n) { if (n <= 3) return -1; if ((n & 1) == 0) return 2; long a = (Math.abs(r.nextLong()) + 2) % 100000, y = (Math.abs(r.nextLong()) + 2) % 100000, x = y, d; do { x = poly(x, a, n); y = poly(poly(y, a, n), a, n); d = gcd(n, Math.abs(x - y)); } while (d == 1); return d; } private static long poly(long x, long a, long n) { return (mulmod(x, x, n) + a) % n; } private static long mulmod(long a, long b, long c) { return BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)).mod(BigInteger.valueOf(c)).longValue(); } static long solve(long[] a, long[] m) { long A = a[0], M = m[0]; for (int i = 1; i < a.length; i++) { if (A > a[i]) { A = A ^ a[i] ^ (a[i] = A); M = M ^ m[i] ^ (m[i] = M); } long gcd = gcd(m[i], M), diff = a[i] - A; if (gcd == 0 || diff % gcd != 0) return -1; long MOD = M * m[i] / gcd; A = (modInv(M / gcd, m[i] / gcd) * (diff / gcd) % MOD * M + A) % MOD; M = MOD; } return A; } private static long modInv(long a, long m) { long m0 = m, t, q, x0 = 0, x1 = 1; while (a > 1) { q = a / (t = m); m = a % m; a = t; x0 = x1 - q * (t = x0); x1 = t; } return (m == 1) ? 0 : (x1 < 0) ? x1 + m0 : x1; } private static long gcd(long a, long b) { return Math.abs(b == 0 ? a : gcd(b, a % b)); } } private static class MST { static int[] root; static int[] rank; static int disjoint; public MST(int num) { root = new int[num]; rank = new int[num]; Arrays.fill(root, -1); disjoint = num; } public static int find(int s) { if (root[s] != s) return root[s] == -1 ? s : (root[s] = find(root[s])); return root[s]; } public static void union(int s, int t) { int x = find(s); int y = find(t); if (x != y) disjoint--; if (rank[x] < rank[y]) { root[x] = y; } if (rank[y] < rank[x]) { root[y] = x; } if (rank[y] == rank[x]) { root[y] = x; rank[x]++; } } } private static class ManachersAlgorithm { public static int[] findLongestPalindrome(String s) { if (s == null || s.length() == 0) return new int[0]; char[] s2 = addBoundaries(s.toCharArray()); int[] p = new int[s2.length]; int c = 0, r = 0; // Here the first element in s2 has been // processed. int m = 0, n = 0; // The walking indices to compare if two elements // are the same for (int i = 1; i < s2.length; i++) { if (i > r) { p[i] = 0; m = i - 1; n = i + 1; } else { int i2 = c * 2 - i; if (p[i2] < (r - i - 1)) { p[i] = p[i2]; m = -1; // This signals bypassing the while loop below. } else { p[i] = r - i; n = r + 1; m = i * 2 - n; } } while (m >= 0 && n < s2.length && s2[m] == s2[n]) { p[i]++; m--; n++; } if ((i + p[i]) > r) { c = i; r = i + p[i]; } } // System.out.println(Arrays.toString(p)); int len = 0; c = 0; for (int i = 1; i < s2.length; i++) { if (len < p[i]) { len = p[i]; c = i; } } char[] ss = Arrays.copyOfRange(s2, c - len, c + len + 1); return p; } private static char[] addBoundaries(char[] cs) { if (cs == null || cs.length == 0) return "||".toCharArray(); char[] cs2 = new char[cs.length * 2 + 1]; for (int i = 0; i < (cs2.length - 1); i = i + 2) { cs2[i] = '|'; cs2[i + 1] = cs[i / 2]; } cs2[cs2.length - 1] = '|'; return cs2; } private static char[] removeBoundaries(char[] cs) { if (cs == null || cs.length < 3) return "".toCharArray(); char[] cs2 = new char[(cs.length - 1) / 2]; for (int i = 0; i < cs2.length; i++) { cs2[i] = cs[i * 2 + 1]; } return cs2; } } static class FFT_Precise { static final int maxk = 21, maxn = (1 << maxk) + 1; // maxk ~ log(maxn) static double[] ws_r = new double[maxn]; static double[] ws_i = new double[maxn]; static int[] dp = new int[maxn]; static double[] rs_r = new double[maxn]; static double[] rs_i = new double[maxn]; static int n, k; static int lastk = -1; static void fft(boolean rev) { if (lastk != k) { lastk = k; dp[0] = 0; for (int i = 1, g = -1; i < n; ++i) { if ((i & (i - 1)) == 0) { ++g; } dp[i] = dp[i ^ (1 << g)] ^ (1 << (k - 1 - g)); } ws_r[1] = 1; ws_i[1] = 0; for (int two = 0; two < k - 1; ++two) { double alf = Math.PI / n * (1 << (k - 1 - two)); double cur_r = Math.cos(alf), cur_i = Math.sin(alf); int p2 = (1 << two), p3 = p2 * 2; for (int j = p2; j < p3; ++j) { ws_r[j * 2] = ws_r[j]; ws_i[j * 2] = ws_i[j]; // ws[j] * cur ws_r[j * 2 + 1] = ws_r[j] * cur_r - ws_i[j] * cur_i; ws_i[j * 2 + 1] = ws_r[j] * cur_i + ws_i[j] * cur_r; } } } for (int i = 0; i < n; ++i) { if (i < dp[i]) { double ar = a_r[i]; double ai = a_i[i]; a_r[i] = a_r[dp[i]]; a_i[i] = a_i[dp[i]]; a_r[dp[i]] = ar; a_i[dp[i]] = ai; } } if (rev) { for (int i = 0; i < n; ++i) { a_i[i] = -a_i[i]; } } for (int len = 1; len < n; len <<= 1) { for (int i = 0; i < n; i += len) { int wit = len; for (int it = 0, j = i + len; it < len; ++it, ++i, ++j) { double tmp_r = a_r[j] * ws_r[wit] - a_i[j] * ws_i[wit]; double tmp_i = a_r[j] * ws_i[wit] + a_i[j] * ws_r[wit]; wit++; a_r[j] = a_r[i] - tmp_r; a_i[j] = a_i[i] - tmp_i; a_r[i] += tmp_r; a_i[i] += tmp_i; // System.out.printf("%3f %3f\n", a_r[j], a_i[j]); // System.out.printf("%3f %3f\n", a_r[i], a_i[i]); } } } // System.out.println(); } static double[] a_r = new double[maxn]; static double[] a_i = new double[maxn]; static long[] mult(long[] _a, long[] _b) { int na = _a.length, nb = _b.length; for (k = 0, n = 1; n < na + nb - 1; n <<= 1, ++k) ; ass(n < maxn); for (int i = 0; i < n; ++i) { a_r[i] = i < na ? _a[i] : 0; a_i[i] = i < nb ? _b[i] : 0; } fft(false); a_r[n] = a_r[0]; a_i[n] = a_i[0]; double r_i = -1.0d / n / 4.0d; for (int i = 0; i <= n - i; ++i) { double tmp_r = a_r[i] * a_r[i] - a_i[i] * a_i[i]; double tmp_i = a_r[i] * a_i[i] * 2.0; double tmp2_r = a_r[n - i] * a_r[n - i] - a_i[n - i] * a_i[n - i]; double tmp2_i = a_r[n - i] * a_i[n - i] * -2.0; tmp_r = tmp_r - tmp2_r; tmp_i = tmp_i - tmp2_i; a_r[i] = -tmp_i * r_i; a_i[i] = tmp_r * r_i; a_r[n - i] = a_r[i]; a_i[n - i] = -a_i[i]; } fft(true); int res = 0; long[] ans = new long[maxn]; // System.out.println(Arrays.toString(a_r)); for (int i = 0; i < n; ++i) { long val = (long) Math.round(a_r[i]); ass(Math.abs(val - a_r[i]) < 1e-1); if (val != 0) { ass(i < na + nb - 1); while (res < i) { ans[res++] = 0; } ans[res++] = val; } } return ans; } static void ass(boolean f) { if (!f) System.out.println(1 / 0); } } private static class Sat2 { static void dfs1(ArrayList<Integer>[] graph, boolean[] used, ArrayList<Integer> order, int u) { used[u] = true; for (int v : graph[u]) { if (!used[v]) { dfs1(graph, used, order, v); } } order.add(u); } static void dfs2(ArrayList<Integer>[] reverseGraph, int[] comp, int u, int color) { comp[u] = color; for (int v : reverseGraph[u]) { if (comp[v] == -1) { dfs2(reverseGraph, comp, v, color); } } } public static boolean[] solve2Sat(ArrayList<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; ArrayList<Integer> order = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (!used[i]) { dfs1(graph, used, order, i); } } ArrayList<Integer>[] reverseGraph = new ArrayList[n]; for (int i = 0; i < n; i++) reverseGraph[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { for (int j : graph[i]) { reverseGraph[j].add(i); } } int[] comp = new int[n]; Arrays.fill(comp, -1); for (int i = 0, color = 0; i < n; i++) { int u = order.get(n - i - 1); if (comp[u] == -1) { dfs2(reverseGraph, comp, u, color++); } } for (int i = 0; i < n; i++) { if (comp[i] == comp[i ^ 1]) return null; } boolean[] res = new boolean[n / 2]; for (int i = 0; i < n; i += 2) res[i / 2] = comp[i] > comp[i ^ 1]; return res; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
cdf80de864dc083735995bdeac1d2ce2
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); int[] a = new int[5009]; int[] l = new int[5009]; int[] r = new int[5009]; String[] input = in.readLine().split("\\s+"); for(int i = 1; i <= n; i++){ a[i] = Integer.parseInt(input[i-1]); if(l[a[i]] == 0) l[a[i]] = i; r[a[i]] = i; } int[] dp = new int[5009]; int[] visited = new int[5009]; for(int i = 1; i <= n; i++){ int xor = 0; int mostLeftIndex = i; for(int j = i; j >= 1; j--){ if(r[a[j]] > i) break; if(visited[a[j]] != i){ xor ^= a[j]; visited[a[j]] = i; } mostLeftIndex = (int) Math.min(mostLeftIndex, l[a[j]]); if(mostLeftIndex == j) dp[i] = (int) Math.max(dp[i], dp[j-1] + xor); } dp[i] = (int) Math.max(dp[i], dp[i-1]); } out.print(dp[n]); in.close(); out.close(); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
510d915378d1325620d97bd3f7ecdbc4
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; public class Main { final static int INF = 1 << 28; final static long MOD = 1_000_000_007; final static double EPS = 1e-9; final static double GOLDEN_RATIO = (1.0 + Math.sqrt(5)) / 2.0; Scanner sc = new Scanner(System.in); public static void main(String[] args) { new Main().run(); } class Node { int left = INF; int right = -1; @Override public String toString() { return "{" + left + ", " + right + "}"; } } void run() { int n = ni(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = ni(); } Node[] map = new Node[5000 + 1]; for (int i = 0; i < n; ++i) { if (map[a[i]] != null) { map[a[i]].right = i; } else { Node node = new Node(); node.left = node.right = i; map[a[i]] = node; } } // debug(map); int[][] table = new int[n][n]; for (int l = 0; l < n; ++l) { int xor = 0; int ok = l; for (int r = l; r < n; ++r) { Node node = map[a[r]]; if (l <= node.left && node.right <= r) { xor ^= a[r]; if (ok <= r) { table[l][r] = xor; } else { table[l][r] = -1; } } else { if (r < node.right) { ok = Math.max(ok, node.right); table[l][r] = -1; } else { for (int j = r; j < n; ++j) { table[l][j] = -1; } r = n - 1; } } } } // debug(table[0][0]); // debug(table[0][1]); // debug(table[2][4]); // debug(table[5][5]); int[] dp = new int[n + 1]; for (int i = 0; i < n; ++i) { dp[i + 1] = Math.max(dp[i + 1], dp[i]); for (int j = i; j < n; ++j) { if (table[i][j] == -1) { continue; } dp[j + 1] = Math.max(dp[j + 1], dp[i] + table[i][j]); } } System.out.println(dp[n]); } int ni() { return Integer.parseInt(sc.next()); } void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } /** * ユークリッドの互除法 * * @return a と b の最大公約数 */ long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } /** * 拡張ユークリッドの互除法 * * @return mx + ny = gcd(m, n)となるような(x, y)を返す */ Pair<Long, Long> gcd_ex(long m, long n) { long[][] mat = _gcd_ex(m, n); return new Pair<>(mat[0][0], mat[0][1]); } long[][] _gcd_ex(long m, long n) { if (n == 0) { return new long[][]{{1, 0}, {0, 1}}; } long k = m / n; long[][] K = new long[][]{{0, 1}, {1, -k}}; long[][] r = _gcd_ex(n, m % n); long[][] dst = new long[2][2]; for (int y = 0; y < 2; ++y) for (int x = 0; x < 2; ++x) for (int i = 0; i < 2; ++i) dst[y][x] += r[y][i] * K[i][x]; return dst; } /** * 繰り返し2乗法を用いたべき乗の実装 * * @return a^r (mod 1,000,000,007) */ long pow(long a, long r) { long sum = 1; while (r > 0) { if ((r & 1) == 1) { sum *= a; sum %= MOD; } a *= a; a %= MOD; r >>= 1; } return sum; } /** * 組み合わせ * O(n) * * @return {}_nC_r */ long C(int n, int r) { long sum = 1; for (int i = n; 0 < i; --i) { sum *= i; sum %= MOD; } long s = 1; for (int i = r; 0 < i; --i) { s *= i; s %= MOD; } sum *= pow(s, MOD - 2); sum %= MOD; long t = 1; for (int i = n - r; 0 < i; --i) { t *= i; t %= MOD; } sum *= pow(t, MOD - 2); sum %= MOD; return sum; } /** * 黄金分割探索 * * @param left 下限 * @param right 上限 * @param f 探索する関数 * @param comp 上に凸な関数を探索するときは、Comparator.comparingDouble(Double::doubleValue) * 下に凸な関数を探索するときは、Comparator.comparingDouble(Double::doubleValue).reversed() * @return 極値の座標x */ double goldenSectionSearch(double left, double right, Function<Double, Double> f, Comparator<Double> comp) { double c1 = divideInternally(left, right, 1, GOLDEN_RATIO); double c2 = divideInternally(left, right, GOLDEN_RATIO, 1); double d1 = f.apply(c1); double d2 = f.apply(c2); while (right - left > 1e-9) { if (comp.compare(d1, d2) > 0) { right = c2; c2 = c1; d2 = d1; c1 = divideInternally(left, right, 1, GOLDEN_RATIO); d1 = f.apply(c1); } else { left = c1; c1 = c2; d1 = d2; c2 = divideInternally(left, right, GOLDEN_RATIO, 1); d2 = f.apply(c2); } } return right; } /** * [a,b]をm:nに内分する点を返す */ double divideInternally(double a, double b, double m, double n) { return (n * a + m * b) / (m + n); } /** * http://alexbowe.com/popcount-permutations/ * bitの立っている数が小さい順にループしたいときに使う。 * ex) * <pre> * for (int i = 0; i < 25; ++i) { * int bits = (1 << i) - 1; * long m = C(25, num); * for (j = 0; j < m; ++j) { * ...(25個の中からi個bitが立っている) * if (bits != 0) * bits = next_perm(bits); * } * } * </pre> * * @param v 現在のbit列 * @return 次のbit列 */ int next_perm(int v) { int t = (v | (v - 1)) + 1; return t | ((((t & -t) / (v & -v)) >> 1) - 1); } /** * from http://gihyo.jp/dev/serial/01/geometry part 6 */ static class Line { double a; double b; double c; /** * 一般形のパラメータから直線を作成する * * @param a xの係数 * @param b yの係数 * @param c 定数項 */ Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } /** * 2点(x1, y1), (x2, y2)を通る直線を作成する * * @param x1 1点目のx座標 * @param y1 1点目のy座標 * @param x2 2点目のx座標 * @param y2 2点目のy座標 * @return 直線 */ static Line fromPoints(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; return new Line(dy, -dx, dx * y1 - dy * x1); } /** * 与えられた直線との交点を返す * * @param l 直線 * @return 交点。2直線が平行の場合はnull */ Point2D getIntersectionPoint(Line l) { double d = a * l.b - l.a * b; if (d == 0.0) { return null; } double x = (b * l.c - l.b * c) / d; double y = (l.a * c - a * l.c) / d; return new Point2D.Double(x, y); } @Override public String toString() { return "a = " + a + ", b = " + b + ", c = " + c; } } /** * from http://gihyo.jp/dev/serial/01/geometry part 6 */ static public class LineSegment { double x1; double y1; double x2; double y2; LineSegment(double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } Line toLine() { return Line.fromPoints(x1, y1, x2, y2); } boolean intersects(Line l) { double t1 = l.a * x1 + l.b * y1 + l.c; double t2 = l.a * x2 + l.b * y2 + l.c; return t1 * t2 <= 0; } boolean intersects(LineSegment s) { return bothSides(s) && s.bothSides(this); } // sが自線分の「両側」にあるかどうかを調べる private boolean bothSides(LineSegment s) { double ccw1 = GeomUtils.ccw(x1, y1, s.x1, s.y1, x2, y2); double ccw2 = GeomUtils.ccw(x1, y1, s.x2, s.y2, x2, y2); if (ccw1 == 0 && ccw2 == 0) { // sと自線分が一直線上にある場合 // sのいずれか1つの端点が自線分を内分していれば、sは自線分と共有部分を持つので // trueを返す return internal(s.x1, s.y1) || internal(s.x2, s.y2); } else { // それ以外の場合 // CCW値の符号が異なる場合にtrueを返す return ccw1 * ccw2 <= 0; } } // (x, y)が自線分を内分しているかどうかを調べる private boolean internal(double x, double y) { // (x, y)から端点に向かうベクトルの内積がゼロ以下であれば内分と見なす return GeomUtils.dot(x1 - x, y1 - y, x2 - x, y2 - y) <= 0; } public Point2D getIntersectionPoint(Line l) { if (!intersects(l)) { return null; // 交差しない場合はnullを返す } return l.getIntersectionPoint(toLine()); } public Point2D getIntersectionPoint(LineSegment s) { if (!intersects(s)) { return null; // 交差しない場合はnullを返す } return s.toLine().getIntersectionPoint(toLine()); } /** * from : http://www.deqnotes.net/acmicpc/2d_geometry/lines#distance_between_line_segment_and_point */ double distance(double x0, double y0) { // 端点チェック if (GeomUtils.dot(x2 - x1, y2 - y1, x0 - x1, y0 - y1) < EPS) { return GeomUtils.abs(x0 - x1, y0 - y1); } if (GeomUtils.dot(x1 - x2, y1 - y2, x0 - x2, y0 - y2) < EPS) { return GeomUtils.abs(x0 - x2, y0 - y2); } // 直線と点の距離 return Math.abs(GeomUtils.cross(x2 - x1, y2 - y1, x0 - x1, y0 - y1)) / GeomUtils.abs(x2 - x1, y2 - y1); } double distance(LineSegment l) { if (this.intersects(l)) { return 0.0; } double min = Double.MAX_VALUE; min = Math.min(min, distance(l.x1, l.y1)); min = Math.min(min, distance(l.x2, l.y2)); min = Math.min(min, l.distance(x1, y1)); min = Math.min(min, l.distance(x2, y2)); return min; } @Override public String toString() { return "(" + x1 + ", " + y1 + ") - (" + x2 + ", " + y2 + ")"; } } /** * from http://gihyo.jp/dev/serial/01/geometry part 6 */ static class GeomUtils { static double cross(double x1, double y1, double x2, double y2) { return x1 * y2 - x2 * y1; } static double dot(double x1, double y1, double x2, double y2) { return x1 * x2 + y1 * y2; } // (x1, y1) -> (x2, y2) -> (x3, y3) と進む道のりが半時計回りの場合は正の値、 // 時計回りの場合は負の値、一直線上の場合はゼロを返す static double ccw(double x1, double y1, double x2, double y2, double x3, double y3) { return cross(x2 - x1, y2 - y1, x3 - x2, y3 - y2); } static double ccw(Point2D p1, Point2D p2, Point2D p3) { return ccw(p1.getX(), p1.getY(), p2.getX(), p2.getY(), p3.getX(), p3.getY()); } static double abs(double x, double y) { return Math.sqrt(x * x + y * y); } } /** * http://qiita.com/p_shiki37/items/65c18f88f4d24b2c528b */ static class FastScanner { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public FastScanner(InputStream in) { this.in = in; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } } static class Pair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<Pair<F, S>> { F f; S s; Pair() { } Pair(F f, S s) { this.f = f; this.s = s; } Pair(Pair<F, S> p) { f = p.f; s = p.s; } @Override public int compareTo(Pair<F, S> p) { if (f.compareTo(p.f) != 0) { return f.compareTo(p.f); } return s.compareTo(p.s); } @Override public int hashCode() { return f.hashCode() ^ s.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || this.f == null || this.s == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair p = (Pair) o; return this.f.equals(p.f) && this.s.equals(p.s); } @Override public String toString() { return "{" + f.toString() + ", " + s.toString() + "}"; } } class BIT<T> { int n; ArrayList<T> bit; BiFunction<T, T, T> bif; /** * 1-indexed なBinary Indexed Treeを構築する * * @param n 容量 * @param bif 適用させる関数 * @param sup 初期値 */ BIT(int n, BiFunction<T, T, T> bif, Supplier<T> sup) { this.n = n; bit = new ArrayList<>(n + 1); for (int i = 0; i < n + 1; ++i) { bit.add(sup.get()); } this.bif = bif; } /** * iの位置の値をvで更新する * * @param i index * @param v 新しい値 */ void set(int i, T v) { for (int x = i; x <= n; x += x & -x) { bit.set(x, bif.apply(bit.get(x), v)); } } /** * クエリー * * @param defaultValue 初期値 * @param i index * @return [1, i]までfを適用した結果 */ T reduce(T defaultValue, int i) { T ret = defaultValue; for (int x = i; x > 0; x -= x & -x) { ret = bif.apply(ret, bit.get(x)); } return ret; } } class SegmentTree<T> { int n; ArrayList<T> dat; BiFunction<T, T, T> bif; Supplier<T> sup; /** * 0-indexed なSegment Treeを構築する * * @param n_ 要求容量 * @param bif 適用させる関数 * @param sup 初期値 */ SegmentTree(int n_, BiFunction<T, T, T> bif, Supplier<T> sup) { n = 1; while (n < n_) n *= 2; dat = new ArrayList<>(2 * n - 1); for (int i = 0; i < 2 * n - 1; ++i) { dat.add(sup.get()); } this.bif = bif; this.sup = sup; } /** * kの位置の値をvで更新する * * @param k index * @param v 新しい値 */ void set(int k, T v) { k += n - 1; dat.set(k, v); while (k > 0) { k = (k - 1) / 2; dat.set(k, bif.apply(dat.get(k * 2 + 1), dat.get(k * 2 + 2))); } } /** * クエリー * * @param l はじめ * @param r おわり * @return [l, r)での演算bifを適用した結果を返す */ T reduce(int l, int r) { return _reduce(l, r, 0, 0, n); } T _reduce(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return sup.get(); if (a <= l && r <= b) return dat.get(k); T vl = _reduce(a, b, k * 2 + 1, l, (l + r) / 2); T vr = _reduce(a, b, k * 2 + 2, (l + r) / 2, r); return bif.apply(vl, vr); } } class UnionFind { int[] par; UnionFind(int n) { par = new int[n]; for (int i = 0; i < n; ++i) { par[i] = i; } } int find(int x) { if (par[x] == x) { return x; } return par[x] = find(x); } boolean same(int x, int y) { return find(x) == find(y); } void union(int x, int y) { x = find(x); y = find(y); if (x == y) { return; } par[x] = y; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
07dfc5bdef685273cec5b326fb3a86cb
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
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; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } } int [][]lastFist = new int[5001][2]; //I will change it on map latly Set<Integer> alreadyIs = new HashSet<>(5002); int getLast(int fist, int []array){ int last = lastFist[array[fist]][1]; for(int i=fist; i<last; i++){ if(alreadyIs.contains(array[i])){ return -1; } last = Math.max(lastFist[array[i]][1],last); } return last; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = (in.nextInt())+1; int []seqPep = new int[n]; int array[] = new int[n]; int []partSum = new int[n]; for(int i=1; i<n; i++){ seqPep[i] = in.nextInt(); array[i] = seqPep[i]; lastFist[seqPep[i]][1]=i;//lastElement if(lastFist[seqPep[i]][0]==0){ lastFist[seqPep[i]][0]=i;//firstElement }else{ seqPep[i]=0; } partSum[i] = partSum[i-1]^seqPep[i]; } int []sumSeg = new int[n]; int []sumSubSeg = new int[n]; Deque<Pair> stack = new LinkedList<>(); int answer = 0; for(int i=1; i<n; i++){ if(!alreadyIs.contains(array[i])){ int last = getLast(i, array); if(last!=-1) { sumSeg[last] = partSum[last] ^ partSum[i - 1]; stack.addLast(new Pair(array[i], last)); } alreadyIs.add(array[i]); } if(stack.peekLast().second==i){// I need a better one stack.pollLast(); if(sumSeg[i]<sumSubSeg[i]){ sumSeg[i]=sumSubSeg[i]; } if(stack.isEmpty()){ answer+=sumSeg[i]; }else{ sumSubSeg[stack.peekLast().second]+=sumSeg[i]; } } } out.println(answer); } } void madAdd(Map <Character, Integer> map, char value){ if(map.containsKey(value)){ map.put(value, map.get(value)+1); }else{ map.put(value, 1); } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() {return Integer.parseInt(next());} public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } public void writeFile1(){ try{ FileWriter write = new FileWriter(file); write.append("100000"+" "); for(int i=0; i<100000; i++){ write.append(new Integer((int)(Math.random()*5000)).toString()+" "); } write.close(); }catch(IOException e){ e.printStackTrace(); } } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
c3041a3dc2c2b23f1c4dd4059ec2ffb8
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
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; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int [][]lastFist = new int[5001][2]; //I will change it on map latly Set<Integer> alreadyIs = new HashSet<>(5002); int getLast(int fist, int []array){ int last = lastFist[array[fist]][1]; for(int i=fist; i<last; i++){ if(alreadyIs.contains(array[i])){ return -1; } last = Math.max(lastFist[array[i]][1],last); } return last; } class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = (in.nextInt())+1; int seqPep[] = new int[n]; int array[] = new int[n]; int []partSum = new int[n]; for(int i=1; i<n; i++){ seqPep[i] = in.nextInt(); array[i] = seqPep[i]; lastFist[seqPep[i]][1]=i;//lastElement if(lastFist[seqPep[i]][0]==0){ lastFist[seqPep[i]][0]=i;//firstElement }else{ seqPep[i]=0; } partSum[i] = partSum[i-1]^seqPep[i]; } int []sumSeg = new int[n]; int []sumSubSeg = new int[n]; //Deque<Integer> stack = new LinkedList<>(); Deque<Pair> stack = new LinkedList<>(); int answer = 0; for(int i=1; i<n; i++){ if(!alreadyIs.contains(array[i])){ int last = getLast(i, array); if(last!=-1) { sumSeg[last] = partSum[last] ^ partSum[i - 1]; // System.out.println(array[i] + " " + last + " " + sumSeg[last]); stack.addLast(new Pair(array[i], last)); } alreadyIs.add(array[i]); } if(!stack.isEmpty() && stack.peekLast().second==i){// I need a better one stack.pollLast(); if(sumSeg[i]<sumSubSeg[i]){ sumSeg[i]=sumSubSeg[i]; } if(stack.isEmpty()){ answer+=sumSeg[i]; }else{ sumSubSeg[stack.peekLast().second]+=sumSeg[i]; } } } out.println(answer); } } void madAdd(Map <Character, Integer> map, char value){ if(map.containsKey(value)){ map.put(value, map.get(value)+1); }else{ map.put(value, 1); } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() {return Integer.parseInt(next());} public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
b26c6a28795120150488e68738fbe2d5
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static final int UNCALC = -1, INF = (int) 1e9; static int n; static int[] memo, a, first, last; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); memo = new int[n]; Arrays.fill(memo, UNCALC); a = new int[n]; first = new int[5001]; last = new int[5001]; Arrays.fill(first, UNCALC); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (first[a[i]] == -1) first[a[i]] = i; last[a[i]] = i; } out.println(dp(0)); out.flush(); out.close(); } static int dp(int i) { if (i == n) return 0; if (memo[i] != UNCALC) return memo[i]; int best = dp(i + 1); int xor = 0, right = last[a[i]], left = first[a[i]]; boolean[] taken = new boolean[5001]; for (int end = i; end < n; end++) { right = Math.max(right, last[a[end]]); left = Math.min(left, first[a[end]]); if (!taken[a[end]]) { taken[a[end]] = true; xor ^= a[end]; } if (end == right && left == i) best = Math.max(best, xor + dp(end + 1)); } return memo[i] = best; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
77da64ad811042778c1aff5ef1e2b69a
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; public class c{ public static void main(String[] arg) throws IOException { new c(); } public c() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] vs = new int[n]; for(int i = 0; i < n; i++) vs[i] = in.nextInt(); int[] dp = new int[n]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); int[] hasLeft = new int[n]; for(int i = 0; i < n; i++) { if(hm.containsKey(vs[i])) hasLeft[i] = hm.get(vs[i]); else { hm.put(vs[i], i); hasLeft[i] = i; } } int[] hasRight = new int[n]; hm.clear(); for(int i = n-1; i >= 0; i--) { if(hm.containsKey(vs[i])) hasRight[i] = hm.get(vs[i]); else { hm.put(vs[i], i); hasRight[i] = i; } } if(hasRight[0] == 0) dp[0] = vs[0]; for(int i = 1; i < n; i++) { dp[i] = dp[i-1]; if(hasRight[i] == i) { int xor = vs[i]; int minLeft = hasLeft[i]; boolean valid = true; for(int j = i-1; j >= 0; j--) { if(minLeft > j) { dp[i] = Math.max(dp[i], dp[j]+xor); } if(hasRight[j] > i) { valid = false; break; } if(hasRight[j] == j) xor ^= vs[j]; minLeft = Math.min(minLeft, hasLeft[j]); } if(valid) dp[i] = Math.max(dp[i], xor); } } out.println(dp[n-1]); in.close(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public void close() throws IOException { br.close(); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
f40ae66482b8d51baae009be8a96669e
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikMemorableTrip2 { int N = 5005; void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] fi = new int[N], la = new int[N]; Arrays.fill(fi, -1); Arrays.fill(la, -1); for (int i = 0; i < n; i++) if (fi[a[i]] < 0) fi[a[i]] = i; for (int i = n - 1; i >= 0; i--) if (la[a[i]] < 0) la[a[i]] = i; int[] dp = new int[n + 1]; for (int i = 0; i < n; i++) { dp[i + 1] = Math.max(dp[i + 1], dp[i]); if (i != la[a[i]]) continue; int lb = fi[a[i]], cur = 0; for (int j = i; j >= 0; j--) { if (la[a[j]] > i) break; lb = Math.min(lb, fi[a[j]]); if (j == la[a[j]]) cur ^= a[j]; if (j == lb) { dp[i + 1] = Math.max(dp[i + 1], dp[lb] + cur); break; } } } out.println(dp[n]); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikMemorableTrip2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
497ee20aa75d73537aa6c14f03430ca3
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikMemorableTrip { int N = 5005; int n; int[] a; int[] fi = new int[N], la = new int[N]; int[] dp = new int[N]; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.fill(fi, -1); Arrays.fill(la, -1); for (int i = 0; i < n; i++) if (fi[a[i]] < 0) fi[a[i]] = i; for (int i = n - 1; i >= 0; i--) if (la[a[i]] < 0) la[a[i]] = i; Arrays.fill(dp, -1); int ans = dfs(n - 1); out.println(ans); } int dfs(int i) { if (i < 0) return 0; if (dp[i] >= 0) return dp[i]; if (i != la[a[i]]) return dfs(i - 1); boolean ok = true; int res = 0, lb = fi[a[i]]; for (int j = i; j >= lb; j--) { if (j == la[a[j]]) res ^= a[j]; if (la[a[j]] > i) { ok = false; break; } lb = Math.min(lb, fi[a[j]]); } if (ok) res += dfs(lb - 1); else res = 0; return dp[i] = Math.max(res, dfs(i - 1)); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikMemorableTrip().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
949678e7aedc6eff79f52eaff6cfd8f0
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikMemorableTrip2 { int N = 5005; void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] fi = new int[N], la = new int[N]; Arrays.fill(fi, -1); Arrays.fill(la, -1); for (int i = 0; i < n; i++) if (fi[a[i]] < 0) fi[a[i]] = i; for (int i = n - 1; i >= 0; i--) if (la[a[i]] < 0) la[a[i]] = i; int[] dp = new int[n + 1]; for (int i = 0; i < n; i++) { dp[i + 1] = Math.max(dp[i + 1], dp[i]); if (i != la[a[i]]) continue; int lb = fi[a[i]], cur = 0; for (int j = i; j >= 0; j--) { if (la[a[j]] > i) break; lb = Math.min(lb, fi[a[j]]); if (j == la[a[j]]) cur ^= a[j]; if (j == lb) dp[i + 1] = Math.max(dp[i + 1], dp[lb] + cur); } } out.println(dp[n]); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikMemorableTrip2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
3265c6f7e5ecdcbbfdc07ef24a263366
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikMemorableTrip { int N = 5005; int n; int[] a; int[] fi = new int[N], la = new int[N]; int[] dp = new int[N]; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.fill(fi, -1); Arrays.fill(la, -1); for (int i = 0; i < n; i++) if (fi[a[i]] < 0) fi[a[i]] = i; for (int i = n - 1; i >= 0; i--) if (la[a[i]] < 0) la[a[i]] = i; Arrays.fill(dp, -1); int ans = dfs(n - 1); out.println(ans); } int dfs(int i) { if (i < 0) return 0; if (dp[i] >= 0) return dp[i]; if (i != la[a[i]]) return dp[i] = dfs(i - 1); boolean ok = true; int res = 0, lb = fi[a[i]]; for (int j = i; j >= lb; j--) { if (j == la[a[j]]) res ^= a[j]; if (la[a[j]] > i) { ok = false; break; } lb = Math.min(lb, fi[a[j]]); } if (ok) res += dfs(lb - 1); else res = 0; dp[i] = Math.max(res, dfs(i - 1)); return dp[i]; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikMemorableTrip().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
64059763ffa4aa256be5a1be7c72cff8
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikMemorableTrip { int N = 5005; int n; int[] a; int[] fi = new int[N], la = new int[N]; int[] dp = new int[N]; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.fill(fi, -1); Arrays.fill(la, -1); for (int i = 0; i < n; i++) if (fi[a[i]] < 0) fi[a[i]] = i; for (int i = n - 1; i >= 0; i--) if (la[a[i]] < 0) la[a[i]] = i; Arrays.fill(dp, -1); int ans = dfs(n - 1); out.println(ans); } int dfs(int i) { if (i < 0) return 0; if (dp[i] >= 0) return dp[i]; if (i != la[a[i]]) return dfs(i - 1); boolean ok = true; int res = 0, lb = fi[a[i]]; boolean[] used = new boolean[N]; for (int j = i; j >= lb; j--) { if (j == la[a[j]]) { res ^= a[j]; used[a[j]] = true; } if (!used[a[j]]) { ok = false; break; } lb = Math.min(lb, fi[a[j]]); } if (ok) res += dfs(lb - 1); else res = 0; return dp[i] = Math.max(res, dfs(i - 1)); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikMemorableTrip().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
069f8606515b072c8379ed36c29f5940
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; /** * * @author usquare */ public class Problem{ static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static Pair[] list; static int[] dp; static int[] arr; static int solve(int n){ if(dp[n]!=-1) return dp[n]; int ans=0; int s=n; int e=list[arr[n]].y; for(int i=s;i<=e;i++){ e=max(e,list[arr[i]].y); if(list[arr[i]].x<s) return 0; } HashSet<Integer> set=new HashSet<>(); int xor=0; for(int i=s;i<=e;i++){ if(set.contains(arr[i])) continue; xor^=arr[i]; set.add(arr[i]); } // debug(s,e,n,xor); for(int i=e+1;i<arr.length;i++) ans=max(ans,solve(i)); ans+=xor; return dp[n]=ans; } public static void main(String[] args) throws FileNotFoundException { in = new InputReader(System.in); out = new PrintWriter(System.out); int n=in.ni(); arr=new int[n+1]; list=new Pair[5001]; for(int i=0;i<list.length;i++) list[i]=new Pair(-1, -1); for(int i=1;i<=n;i++){ arr[i]=in.ni(); if(list[arr[i]].x==-1) list[arr[i]].x=list[arr[i]].y=i; else list[arr[i]].y=i; } dp=new int[n+1]; Arrays.fill(dp, -1); int mx=0; for(int i=1;i<=n;i++) mx=max(mx,solve(i)); // debug(dp); out.println(mx); out.close(); } static class Pair implements Comparable<Pair>{ int x; int y,i; Pair (int x,int y,int i){ this.x=x; this.y=y; this.i=i; } Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { return Long.compare(this.y,o.y); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y && p.i==i; } return false; } @Override public String toString() { return x+" "+y+" "+i; } } static class Merge { public static void sort(int inputArr[]) { int length = inputArr.length; doMergeSort(inputArr,0, length - 1); } private static void doMergeSort(int[] arr,int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; doMergeSort(arr,lowerIndex, middle); doMergeSort(arr,middle + 1, higherIndex); mergeParts(arr,lowerIndex, middle, higherIndex); } } private static void mergeParts(int[]array,int lowerIndex, int middle, int higherIndex) { int[] temp=new int[higherIndex-lowerIndex+1]; for (int i = lowerIndex; i <= higherIndex; i++) { temp[i-lowerIndex] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (temp[i-lowerIndex] < temp[j-lowerIndex]) { array[k] = temp[i-lowerIndex]; i++; } else { array[k] = temp[j-lowerIndex]; j++; } k++; } while (i <= middle) { array[k] = temp[i-lowerIndex]; k++; i++; } while(j<=higherIndex){ array[k]=temp[j-lowerIndex]; k++; j++; } } } static long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ a%=mod; b%=mod; long x=(a*b); return x%mod; } static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y){ if(x%y==0) return y; else return gcd(y,x%y); } static int gcd(int x,int y){ if(x%y==0) return y; else return gcd(y,x%y); } static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } static long mulmod(long a,long b,long m) { if (m <= 1000000009) return a * b % m; long res = 0; while (a > 0) { if ((a&1)!=0) { res += b; if (res >= m) res -= m; } a >>= 1; b <<= 1; if (b >= m) b -= m; } return res; } static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } static int max(int a,int b){ if(a>b) return a; else return b; } static int min(int a,int b){ if(a>b) return b; else return a; } static long max(long a,long b){ if(a>b) return a; else return b; } static long min(long a,long b){ if(a>b) return b; else return a; } static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static long pow(long n,long p){ long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { 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
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
0cb4e90f397e07530b9dca71e17d5c0c
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Codechef{ static FR in; public static void main(String[] args)throws Exception{ in =new FR(); int n=ni(); int[]a=ia(n); boolean[]vis; int[]fir=new int[5005]; int[]lst=new int[5005]; for( int i=0;i<n;i++ ) lst[a[i]]=i; for( int i=n-1;i>=0;i-- ) fir[a[i]]=i; int[]dp=new int[n+2]; for( int i=0;i<n;i++ ){ if( lst[a[i]]!=i ){ dp[i+1]=dp[i]; continue; } vis=new boolean[5001]; int min=fir[a[i]]; boolean valid=true; for( int j=i; valid && j>=min; j-- ){ if( lst[a[j]]>lst[a[i]] ) valid=false; vis[a[j]]=true; min=Math.min(min, fir[a[j]] ); } if( valid ){ int inti=0; for( int j=0;j<vis.length;j++ )if( vis[j] )inti^=j; dp[i+1] = Math.max( dp[i], dp[min]+inti ); }else dp[i+1]=dp[i]; }pn(dp[n]); } static long M=(long)1e9+7; static long[]la( int N ){ long[]a=new long[N]; for( int i=0;i<N;i++ )a[i]=nl(); return a; } static int[] ia(int N){ int[] a = new int[N+1]; for(int i = 0; i<N; i++)a[i] = ni(); return a; } static class FR{ BufferedReader br; StringTokenizer st; public FR(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } static void p(Object o){ System.out.print(o); } static void pn(Object o){ System.out.println(o); } static String n(){ return in.next(); } static String nln(){ return in.nextLine(); } static int ni(){ return Integer.parseInt(in.next()); } static long nl(){ return Long.parseLong(in.next()); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
7f35eafcd3ed17a92cedc776b4a16a76
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; public final class C811 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] numbers = new int[n + 1]; int[] max = new int[5001]; int[] min = new int[5001]; int[] dp = new int[5001]; for (int i = 0; i <= 5000; i++) { min[i] = 10000000; } for (int i = 1; i <= n; i++) { int a = in.nextInt(); max[a] = Math.max(i, max[a]); min[a] = Math.min(i, min[a]); numbers[i] = a; } for (int i = 1; i <= n; i++) { dp[i] = dp[i - 1]; int xor = 0; boolean valid = true; int mini = min[numbers[i]]; Set<Integer> set = new HashSet<>(); for (int j = i; j >= mini; j--) { if (max[numbers[j]] > i) { valid = false; break; } set.add(numbers[j]); mini = Math.min(mini, min[numbers[j]]); } if (valid) { for (Integer e : set) { xor ^= e; } } dp[i] = Math.max(dp[i], dp[mini - 1] + xor); } System.out.println(dp[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
320f48af432704579e3334d2406579ce
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int n; static int[] num; static int[] min, max, D; static int Answer; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; n = Integer.parseInt(br.readLine()); min = new int[5001]; max = new int[5001]; num = new int[n+1]; st = new StringTokenizer(br.readLine()); for(int i=1;i<=n;i++){ num[i] = Integer.parseInt(st.nextToken()); if(min[num[i]]==0) min[num[i]] = i; max[num[i]] = i; } D = new int[n+1]; boolean[] chk = new boolean[5001]; for(int i=1;i<=n; i++) { D[i]=D[i - 1]; if(i==max[num[i]]){ int j=i, sum=0, k=min[num[i]]; boolean ok = true; while(j>=k){ if(!chk[num[j]]) { sum ^= num[j]; k = Math.min(k, min[num[j]]); if(max[num[j]] > i){ ok = false; break; } chk[num[j]] = true; } j--; } if(ok) D[i] = Math.max(D[i], D[j] + sum); for(int m=1;m<=i;m++) chk[num[m]] = false; } } Answer = D[n]; System.out.println(Answer); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
b582da7ccb5d79c2b7c1eff0b2dc6b8a
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.Scanner; /** * Created by huang on 17-5-30. */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), a[] = new int[n+1],l[] = new int[5001], r[] = new int[5001]; for (int i = 0; i <= 5000; i++) { l[i] = Integer.MAX_VALUE; } for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); l[a[i]] = Math.min(l[a[i]], i); r[a[i]] = Math.max(r[a[i]], i); } int[] dp = new int[n+1]; boolean[] isVisited = new boolean[5001]; for (int i = 1; i <= n; i++) { dp[i] = Math.max(dp[i], dp[i-1]); int L = l[a[i]], R = r[a[i]], t = a[i]; if (R > i) { continue; } for (int j = 0; j < 5001; j++) { isVisited[j] = false; } isVisited[a[i]] = true; for (int j = i; j > 0; j--) { if (!isVisited[a[j]]) { isVisited[a[j]] = true; t ^= a[j]; } L = Math.min(L, l[a[j]]); R = Math.max(R, r[a[j]]); if (L == j && R == i) { dp[i] = Math.max(dp[j-1]+t, dp[i]); } if (R > i) { break; } } } System.out.println(dp[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
21bf2ebef36dbc406abb14af1ee66a7e
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; public class CF416C { public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); /*------------------------------My Code starts here------------------------------*/ int n=in.nextInt(),i=0,j; int[] a=nextIntArray(in, n); int[] dp=new int[n+1]; dp[0]=0; Map<Integer, Integer> interval=new HashMap<>(); Map<Integer, Integer> end=new HashMap<>(); Set<Integer> st=new HashSet<>(); for(i=n-1;i>=0;i--) { if(!st.contains(a[i])) { end.put(a[i], i); interval.put(i, i); st.add(a[i]); } else interval.put(end.get(a[i]), i); } for(i=0;i<n;i++) { if(interval.containsKey(i)) { Set<Integer> s=new HashSet<>(); int xor=0,start=interval.get(i),finish=i; boolean valid=true; for(j=i;j>=start;j--) { start=Math.min(start, interval.get(end.get(a[j]))); if(end.get(a[j])>i) { dp[i+1]=dp[i]; finish=end.get(a[j]); start=Math.min(j,interval.get(end.get(a[j]))); interval.put(finish,start); end.put(a[start], finish); valid=false; break; } if(!s.contains(a[j])) { xor^=a[j]; s.add(a[j]); } } if(valid) dp[i+1]=Math.max(dp[i], dp[j+1]+xor); } else dp[i+1]=dp[i]; } out.println(dp[n]); out.close(); /*------------------------------The End------------------------------------------*/ } public static final long l = (int) (1e9 + 7); private static int[] nextIntArray(InputReader in, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); return a; } private static long[] nextLongArray(InputReader in, int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = in.nextLong(); return a; } private static int[][] nextIntMatrix(InputReader in, int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) a[i][j] = in.nextInt(); } return a; } private static void show(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } private static void show2DArray(char[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) System.out.print(a[i][j]); System.out.println(); } } static class Pair { private int first; private int second; public Pair(int i, int j) { this.first = i; this.second = j; } public int getFirst() { return first; } public int getSecond() { return second; } public void setFirst(int k) { this.first = k; } public void setSecond(int k) { this.second = k; } } static int modPow(int a, int b, int p) { int result = 1; a %= p; while (b > 0) { if ((b & 1) != 0) result = (result * a) % p; b = b >> 1; a = (a * a) % p; } return result; } public static void SieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[1] = false; int i, j; for (i = 2; i * i <= n; i++) { if (prime[i]) { for (j = i; j <= n; j += i) { if (j != i) prime[i] = false; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
5f6defd96dbebb56e2c1e115b41c1ea1
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; public class CF416C { public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); /*------------------------------My Code starts here------------------------------*/ int n=in.nextInt(),i=0,j; int[] a=nextIntArray(in, n); int[] dp=new int[n+1]; dp[0]=0; Map<Integer, Integer> interval=new HashMap<>(); Map<Integer, Integer> end=new HashMap<>(); Set<Integer> st=new HashSet<>(); for(i=n-1;i>=0;i--) { if(!st.contains(a[i])) { end.put(a[i], i); interval.put(i, i); st.add(a[i]); } else interval.put(end.get(a[i]), i); } for(i=0;i<n;i++) { if(interval.containsKey(i)) { Set<Integer> s=new HashSet<>(); int xor=0,start=interval.get(i),finish=i; boolean valid=true; for(j=i;valid && j>=start;j--) { if(end.get(a[j])>i) valid=false; start=Math.min(start, interval.get(end.get(a[j]))); if(!s.contains(a[j])) { xor^=a[j]; s.add(a[j]); } } if(valid) dp[i+1]=Math.max(dp[i], dp[j+1]+xor); else dp[i+1]=dp[i]; } else dp[i+1]=dp[i]; } out.println(dp[n]); out.close(); /*------------------------------The End------------------------------------------*/ } public static final long l = (int) (1e9 + 7); private static int[] nextIntArray(InputReader in, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); return a; } private static long[] nextLongArray(InputReader in, int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = in.nextLong(); return a; } private static int[][] nextIntMatrix(InputReader in, int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) a[i][j] = in.nextInt(); } return a; } private static void show(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } private static void show2DArray(char[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) System.out.print(a[i][j]); System.out.println(); } } static class Pair { private int first; private int second; public Pair(int i, int j) { this.first = i; this.second = j; } public int getFirst() { return first; } public int getSecond() { return second; } public void setFirst(int k) { this.first = k; } public void setSecond(int k) { this.second = k; } } static int modPow(int a, int b, int p) { int result = 1; a %= p; while (b > 0) { if ((b & 1) != 0) result = (result * a) % p; b = b >> 1; a = (a * a) % p; } return result; } public static void SieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[1] = false; int i, j; for (i = 2; i * i <= n; i++) { if (prime[i]) { for (j = i; j <= n; j += i) { if (j != i) prime[i] = false; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
f2c768b37bd595d42639d7e96cfcf548
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class P { static int[] dp; static int[] a; static int[] lOcc, rOcc; static int MAXN = 5001; static int N; static int[] pre; static int solve(int cur) { // System.out.println(cur); if (cur >= N) return 0; if (dp[cur] != -1) return dp[cur]; // leave int ret = solve(cur + 1); int left = cur, r = rOcc[a[cur]]; boolean validRange = true; // check validity for (int i = left; i <= r && validRange; i++) { if (lOcc[a[i]] < left) validRange = false; // update right border r = Math.max(r, rOcc[a[i]]); } if (validRange) // take range from cur to r ret = Math.max(ret, solve(r + 1) + (pre[r] ^ (left == 0 ? 0 : pre[left - 1]))); return dp[cur] = ret; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); a = sc.nextIntArray(N); lOcc = new int[MAXN]; Arrays.fill(lOcc, 100000); rOcc = new int[MAXN]; Arrays.fill(rOcc, -1); Arrays.fill(rOcc, -1); for (int i = 0; i < N; i++) { lOcc[a[i]] = Math.min(lOcc[a[i]], i); rOcc[a[i]] = Math.max(rOcc[a[i]], i); } // System.out.println(Arrays.toString(rOcc)); pre = new int[N]; pre[0] = a[0]; for (int i = 1; i < N; i++) { pre[i] = pre[i - 1]; if (lOcc[a[i]] == i) pre[i] ^= a[i]; } dp = new int[N + 1]; Arrays.fill(dp, -1); out.println(solve(0)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
c8ad200056901f6954e10300ad3e465a
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; public class C{ static final int C = (int)5e3 + 10; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n], cnt = new int[C]; for (int i = 0; i < n; i++){ a[i] = sc.nextInt(); cnt[a[i]]++; } int[] d = new int[n+1]; for (int i = 0; i < n; i++){ d[i+1] = d[i]; int[] temp = new int[C]; int bad = 0, x = 0; for (int l = i; l >= 0; l--){ temp[a[l]]++; if (temp[a[l]] == 1){ bad++; x ^= a[l]; } if (temp[a[l]] == cnt[a[l]]) bad--; if (bad == 0) d[i+1] = Math.max(d[i+1], x+d[l]); } } System.out.println(d[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
9820cdd18355a9e0126ae7ca59a151a2
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; /* 5 4 2 5 2 3 */ public class C416 { static int[] a; static int[] memo; static int[] max; static int[] min; public static void main(String[] args) throws IOException { FastScanner qwe = new FastScanner(System.in); int n = qwe.nextInt(); a = new int[n+1]; min = new int[5001]; Arrays.fill(min, Integer.MAX_VALUE); max = new int[5001]; for (int i = 1; i < a.length; i++) { a[i] = qwe.nextInt(); min[a[i]] = Math.min(min[a[i]], i); max[a[i]] = Math.max(max[a[i]], i); } memo = new int[n+1]; Arrays.fill(memo, -1); System.out.println(dp(1)); qwe.close(); } static int dp(int at){ if(at == memo.length) return 0; if(memo[at] != -1) return memo[at]; //System.out.println("at: " + at + " a[at] " + a[at]); int best = dp(at+1); int xor = 0; int l = Integer.MIN_VALUE; for(int go = at; go < a.length; go++){ l = Math.max(l, max[a[go]]); if(go == min[a[go]]){ xor ^= a[go]; } else if(min[a[go]] < at){ break; } if(l == go){ //System.out.println("at: " + at + " going to " + (go+1) + " xor: " + xor + " go " + go + " mingo " + min[go]); best = Math.max(best, xor+dp(go+1)); } } return memo[at] = best; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public void close() throws IOException { br.close(); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
c85b3b169ce0f35980c010faaec77bd8
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces811C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sp = br.readLine().split(" "); int n = Integer.parseInt(sp[0]); int[] a = new int[n]; sp = br.readLine().split(" "); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(sp[i]); } int[] prevIndex = new int[n]; int[] lastIndex = new int[5001]; for (int i = 0; i < 5001; i++) { lastIndex[i] = -1; } for (int i = 0; i < n; i++) { prevIndex[i] = lastIndex[a[i]]; lastIndex[a[i]] = i; } int[] block = new int[n]; for (int i = 0; i < n; i++) { if (prevIndex[i] == -1) block[i] = i; else { block[i] = block[prevIndex[i]]; for (int j = prevIndex[i]+1; j < i; j++) { block[i] = Math.min(block[i], block[j]); } } } int[][] blocks = new int[5001][3]; int counter = 0; for (int i = 0; i < 5001; i++) { boolean bool = true; if (lastIndex[i] != -1) { blocks[counter][1] = lastIndex[i]; blocks[counter][0] = block[lastIndex[i]]; blocks[counter][2] = 0; int[] lst = Arrays.copyOfRange(a, block[lastIndex[i]], lastIndex[i]+1); for (int j = 0; j <= lastIndex[i]-block[lastIndex[i]]; j++) { if (lastIndex[lst[j]] == j+block[lastIndex[i]]) { blocks[counter][2] ^= lst[j]; } if (lastIndex[lst[j]] > lastIndex[i]) { bool = false; } } if (bool) counter++; else { blocks[counter][0] = 0; blocks[counter][1] = 0; blocks[counter][2] = 0; } } } for (int i = counter; i < 5001; i++) { blocks[i][1] = 5001; } int[][] blocks2 = keysort(blocks, 1); int[] l = new int[counter]; for (int i = 0; i < counter; i++) { l[i] = blocks2[i][1]; } int[] dp = new int[n]; if (blocks2[0][1] == 0) { dp[0] = blocks2[0][2]; } else { dp[0] = 0; } for (int i = 1; i < n; i++) { int r = findIndex(i, l); if ((r < counter) && (l[r] == i)) { if (blocks2[r][0] > 0) dp[i] = Math.max(dp[i-1], blocks2[r][2] + dp[blocks2[r][0]-1]); else dp[i] = Math.max(dp[i-1], blocks2[r][2]); } else { dp[i] = dp[i-1]; } } System.out.println(dp[n-1]); } public static int findIndex(int n, int[] list) { int r = list.length; if (n > list[r-1]) return r; else if (r == 1) { return 0; } else { int low = 0; int high = r-1; int val = 0; while (low < high) { val = (low+high)/2; if (list[val] == n) return val; else if (list[val] > n) high = val; else low = val+1; } return high; } } public static int[][] keysort(int[][] lst, int key) { int n = lst.length; if (n == 1) { return lst; } int m = n/2; int[][] lst1 = keysort(Arrays.copyOfRange(lst, 0, m), key); int[][] lst2 = keysort(Arrays.copyOfRange(lst, m, n), key); int[][] lstNew = new int[n][2]; int counter1 = 0; int counter2 = 0; while ((counter1 < m) && (counter2 < n-m)) { if (lst1[counter1][key] <= lst2[counter2][key]) { lstNew[counter1+counter2] = lst1[counter1]; counter1++; } else { lstNew[counter1+counter2] = lst2[counter2]; counter2++; } } while (counter1 < m) { lstNew[counter1+counter2] = lst1[counter1]; counter1++; } while (counter2 < n-m) { lstNew[counter1+counter2] = lst2[counter2]; counter2++; } return lstNew; } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
5045243f37da0a3c681c141e778e4bdc
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class hc { InputStream is; PrintWriter out; static class Pair implements Comparable<Pair>{ int x,y,k,i; Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { if(this.x!=o.x) return this.x-o.x; else return this.y-o.y; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y && p.k==k; } return false; } @Override public String toString() { return "("+x + " " + y +" "+k+" "+i+" )"; } } long mod=pow(10,9)+7; static boolean prime[]; static ArrayList<Integer> al[]; static int max=100000; int a[],dp[],l[],r[]; void solve() { int n=ni(); a=na(n); l=new int[n]; r=new int[n]; dp=new int[n]; Arrays.fill(dp,-1); Arrays.fill(r,-1); Arrays.fill(l,-1); int freq[]=new int[5000+1]; Arrays.fill(freq,-1); for(int i=0;i<n;i++) { if(freq[a[i]]==-1) freq[a[i]]=i; else l[i]=freq[a[i]]; } Arrays.fill(freq,-1); for(int i=n-1;i>=0;i--) { if(freq[a[i]]==-1) freq[a[i]]=i; else r[i]=freq[a[i]]; } out.println(rec(n-1)); } int rec(int index) { if(index<0) return 0; if(dp[index]!=-1) return dp[index]; dp[index]=Math.max(dp[index],rec(index-1)); if(r[index]==-1) { int left=l[index]; if(left==-1&&r[index]==-1) dp[index]=Math.max(dp[index],rec(index-1)+a[index]); else { boolean visited[]=new boolean[5000+1]; int xor=0,state=0; for(int i=index;i>=left;i--) { if(r[i]!=-1&&r[i]>index) { state=1; break; } if(l[i]!=-1) left=Math.min(left,l[i]); if(!visited[a[i]]) { xor^=a[i]; visited[a[i]]=true; } } if(state==0) dp[index]=Math.max(dp[index],rec(left-1)+xor); } } return dp[index]; } public static void dev() { al=new ArrayList[max+1]; for(int i=0;i<=max;i++) al[i]=new ArrayList<Integer>(); for(int i=1;i<=max;i++) { for(int j=i;j<=max;j+=i) al[j].add(i); } } public static void prime(int n) { prime=new boolean[n+1]; int count=0; for(int i=2;i*i<=n;i++) { if(prime[i]) continue; for(int j=i;j*i<=n;j++) { prime[i*j]=true; } } } public static int count(int num) { int count=0; while(num!=0) { num=num&(num-1); count++; } return count; } /*static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative }*/ public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(x%y==0) return y; else return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new hc().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
ce50c3ffc5e9a22aeb1aadf18ebf3a44
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C416 { static int n; static int a[]; static int last[]; static int first[]; static boolean illegal[][]; static int comf[][]; static final int N = 5001; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextInt(); } last = new int[n]; for(int i = 0; i < n; ++i) { for(int j = i; j < n; ++j) { if(a[j] == a[i]) { last[i] = j; } } } first = new int[n]; for(int i = 0; i < n; ++i) { for(int j = i; j >= 0; --j) { if(a[j] == a[i]) { first[i] = j; } } } illegal = new boolean[n][n]; comf = new int[n][n]; for(int i = 0; i < n; ++i) { int curComf = 0; boolean used[] = new boolean[N]; int ll = i; int rr = i; for(int j = i; j < n; ++j) { if(!used[a[j]]) { curComf ^= a[j]; used[a[j]] = true; } ll = Integer.min(ll, first[j]); rr = Integer.max(rr,last[j]); if(ll >= i && rr <= j) { comf[i][j] = curComf; } else { illegal[i][j] = true; } } } int maxComf[] = new int[n + 1]; for(int i = 0; i < n; ++i) { maxComf[i + 1] = maxComf[i]; for(int j = i; j >= 0; --j) { if(!illegal[j][i]) { maxComf[i + 1] = Integer.max(maxComf[i + 1], maxComf[j] + comf[j][i]); } } } System.out.println(maxComf[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
b5db810e207544c2d3d561ffb765ad50
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.util.*; public class C416_ { static int n; static int a[]; static int comf[]; static int first[]; static int last[]; static int maxA; static int interval[]; static ArrayList<Interval> intervals; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextInt(); maxA = Integer.max(maxA, a[i]); } first = new int[maxA + 1]; last = new int[maxA + 1]; interval = new int[maxA + 1]; Arrays.fill(first, n); Arrays.fill(last, -1); Arrays.fill(interval, -1); for(int i = 0; i < n; ++i) { first[a[i]] = Integer.min(first[a[i]], i); last[a[i]] = Integer.max(last[a[i]], i); } // System.out.println(Arrays.toString(first)); // System.out.println(Arrays.toString(last)); solve(); System.out.println(comf[comf.length - 1]); } static void solve() { intervals = new ArrayList<>(); ArrayList<Integer> set = new ArrayList<>(); for(int i = 0; i <= maxA; ++i) { if(last[i] != -1) { set.add(i); } } set.sort((a,b) -> Integer.compare(last[a] - first[a], last[b] - first[b])); //if(n==5000) System.out.println(set.size()); for(int i = 0; i < set.size(); i++) { if(interval[set.get(i)] == -1) { calc(set.get(i)); } } Collections.sort(intervals); int m = intervals.size(); if(m == 0) { comf = new int[] {0}; return; } comf = new int[m]; comf[0] = intervals.get(0).xor; for(int i = 1; i < m; ++i) { comf[i] = comf[i - 1]; // bin search of last interval that do not overlap this interval int l = 0; int r = i - 1; while(l < r) { int mid = (l + r + 1) / 2; if(intervals.get(mid).r < intervals.get(i).l) { l = mid; } else { r = mid - 1; } } if(intervals.get(l).r < intervals.get(i).l) { comf[i] = Integer.max(comf[i], comf[l] + intervals.get(i).xor); } else { comf[i] = Integer.max(comf[i], intervals.get(i).xor); } // System.out.println(intervals.get(i).val + " " + comf[i]); } } static void calc(int val) { int num = intervals.size(); interval[val] = num; int l = first[val]; int r = last[val]; int xor = val; int i = l + 1; // moves forward int j = l; // moves backward int k = 5000; while(k >= 0 && (i < r || j > l)) { k--; int cur; boolean forward = false; if(i < r) { cur = a[i]; i++; forward = true; } else { cur = a[j]; j--; } if(interval[cur] == -1) {//first[cur] < l || last[cur] > r) { interval[cur] = num; xor ^= cur; l = Integer.min(l, first[cur]); r = Integer.max(r,last[cur]); } else //{ // if(interval[cur] == -1) { // System.out.println(forward + " Error " + cur + " not used yet."); // System.out.println(first[val] + " " + last[val]); // System.out.println(l + " " + r); // System.out.println(first[cur] + " " + last[cur]); // } else if(interval[cur] != num) { xor ^= intervals.get(interval[cur]).xor; if(forward) { i = intervals.get(interval[cur]).r + 1; } else { j = intervals.get(interval[cur]).l - 1; } // } } } if(i < r || j > l) { System.out.println("k == " + k); } intervals.add(new Interval(l, r, xor)); // System.out.println(intervals); } static class Interval implements Comparable<Interval> { int l; int r; int xor; Interval(int l, int r, int xor) { this.l = l; this.r = r; this.xor = xor; } @Override public int compareTo(Interval arg0) { return Integer.compare(r, arg0.r); } @Override public String toString() { return "[l=" + l + ",r=" + r + ",xor=" + xor + "]"; } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
c6a272c18b88664e00785e1ba7976017
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
//package CR416; import java.util.Arrays; import java.util.Scanner; public class C416 { static int n; static int a[]; static int last[]; static int first[]; static boolean legal[][]; static final int N = 5001; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nextInt(); } last = new int[n]; for(int i = 0; i < n; ++i) { for(int j = i; j < n; ++j) { if(a[j] == a[i]) { last[i] = j; } } } first = new int[n]; for(int i = 0; i < n; ++i) { for(int j = i; j >= 0; --j) { if(a[j] == a[i]) { first[i] = j; } } } legal = new boolean[n][n]; for(int i = 0; i < n; ++i) { int ll = i; int rr = i; for(int j = i; j < n; ++j) { ll = Integer.min(ll, first[j]); rr = Integer.max(rr,last[j]); if(ll >= i && rr <= j) { legal[i][j] = true; } } } int comf[] = new int[n + 1]; for(int i = 0; i < n; ++i) { comf[i + 1] = comf[i]; int cur = 0; boolean used[] = new boolean[N]; for(int j = i; j >= 0; --j) { if(!used[a[j]]) { used[a[j]] = true; cur ^= a[j]; } if(legal[j][i]) { comf[i + 1] = Integer.max(comf[i + 1], comf[j] + cur); } } } System.out.println(comf[n]); } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
d0a98d51d8fe4ef60324a0021613a633
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Abood2B { static int N; static int[] a, F, A, memo; static int[] XOR; static int solve(int i) { if(i >= N) return 0; if(memo[i] != -1) return memo[i]; int ans = solve(i + 1); int l = A[i]; boolean can = true; for (int j = i; j <= l && can; j++) { if(F[j] < i) can = false; l = Math.max(l, A[j]); } if(can) { int x = XOR[l]; if(i > 0) x ^= XOR[i - 1]; ans = Math.max(ans, x + solve(l + 1)); } return memo[i] = ans; } public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); a = new int[N]; for (int i = 0; i < N; i++) a[i] = sc.nextInt(); int[] idx = new int[5001]; F = new int[N]; Arrays.fill(idx, -1); for (int i = 0; i < N; i++) { if(idx[a[i]] == -1) idx[a[i]] = i; F[i] = idx[a[i]]; } Arrays.fill(idx, -1); A = new int[N]; for (int i = N - 1; i >= 0; i--) { if(idx[a[i]] == -1) idx[a[i]] = i; A[i] = idx[a[i]]; } XOR = new int[N]; XOR[0] = a[0]; for (int i = 1; i < N; i++) { XOR[i] = XOR[i - 1]; if(F[i] == i) XOR[i] ^= a[i]; } memo = new int[N]; Arrays.fill(memo, -1); out.println(solve(0)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System){ br = new BufferedReader(new InputStreamReader(System));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
8f0713380855d925c271bab5b4e346ce
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lebegio */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyReader in = new MyReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int[] arr; int[] xor; HashMap<Integer, int[]> map; long[] dp = new long[6000]; public void solve(int testNumber, MyReader in, PrintWriter out) { int n = in.nextInt(); arr = new int[n]; xor = new int[n]; map = new HashMap<>(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); if (set.contains(arr[i])) { xor[i] = xor[i - 1]; } else { xor[i] = arr[i]; if (i > 0) xor[i] ^= xor[i - 1]; set.add(arr[i]); } map.put(arr[i], new int[]{-1, -1, 0}); } for (int i = 0; i < n; i++) { if (map.get(arr[i])[0] == -1) { map.get(arr[i])[0] = i; map.get(arr[i])[1] = i; } else { map.get(arr[i])[1] = i; } } HashSet<Integer> checked = new HashSet<>(); for (int i = 0; i < n; i++) { if (checked.contains(arr[i])) continue; checked.add(arr[i]); int last = map.get(arr[i])[1]; for (int j = i; j <= last; j++) { if (map.get(arr[j])[0] < i) { last = -1; break; } last = Math.max(last, map.get(arr[j])[1]); } map.get(arr[i])[2] = last; } Arrays.fill(dp, -1); long M = calcFrom(0); out.println(M); } long calcFrom(int from) { if (from > arr.length) return 0; if (dp[from] != -1) return dp[from]; long max = 0; int m = 0; for (int i = from; i < arr.length; i++) { if (map.get(arr[i])[2] == -1 || map.get(arr[i])[0] < i) { continue; } int last = map.get(arr[i])[2]; int x = xor[last]; if (i > 0) x ^= xor[i - 1]; m = last + 1; max = Math.max(max, x + calcFrom(m)); } dp[from] = max; return max; } } static class MyReader { private BufferedReader buffReader; private StringTokenizer strTokenizer; private static final int SIZE = 32768; public MyReader(InputStream inputStream) { buffReader = new BufferedReader(new InputStreamReader(inputStream), SIZE); } public String next() { if (strTokenizer == null || !strTokenizer.hasMoreTokens()) { try { strTokenizer = new StringTokenizer(buffReader.readLine().trim()); } catch (IOException e) { throw new RuntimeException(e); } } return strTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
5787ecdee67c142a2c68548b620cc1a8
train_001.jsonl
1495877700
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { static int memo []; static int n; static int [] arr, max, min; static int dp (int start) { if (start == n) return 0; if (memo[start] != -1) return memo[start]; int res = dp(start + 1); int cumXOR = 0; HashSet<Integer> set = new HashSet<>(); for (int i = start;i < n;) { int left = min[arr[i]], right = max[arr[i]]; for (int j = left; j <= right; j++) { left = Math.min(left, min[arr[j]]); right = Math.max(right, max[arr[j]]); if (!set.contains(arr[j])) { set.add(arr[j]); cumXOR ^= arr[j]; } } if (left >= i) { res = Math.max(res, cumXOR + dp(right + 1)); i = right + 1; } else break; } return memo[start] = res; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); arr = new int[n]; min = new int[5001]; max = new int[5001]; Arrays.fill(min, Integer.MAX_VALUE); Arrays.fill(max, Integer.MIN_VALUE); for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); min[arr[i]] = Math.min(min[arr[i]], i); max[arr[i]] = Math.max(max[arr[i]], i); } memo = new int[n]; Arrays.fill(memo, -1); out.println(dp(0)); out.flush(); out.close(); } static class Pair { int left, right, XOR; Pair (int l, int r, int X) { left = l; right = r; XOR = X; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n4 4 2 5 2 3", "9\n5 1 3 1 5 2 4 2 5"]
2 seconds
["14", "9"]
NoteIn the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
Java 8
standard input
[ "dp", "implementation" ]
158a9e5471928a9c7b4e728b68a954d4
First line contains single integer n (1 ≤ n ≤ 5000) — number of people. Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
1,900
The output should contain a single integer — maximal possible total comfort.
standard output
PASSED
7fa9cdd0b20e281533daa03c68059c36
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for(int i = 0; i<q; i++) { long k = in.nextLong(); long n = in.nextLong(); long a = in.nextLong(); long b = in.nextLong(); long c = k-n*a; long o = k-n*b; if(c > 0) { System.out.println(n); continue; } if(o<0) { System.out.println("-1"); continue; } long d = a-b; long corrections = (long)Math.ceil((-c+1)/(1.0*d)); //System.out.println(c + " " + corrections); long answer = n - corrections; System.out.println(answer); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
f7917bc0b03bfb275a406d2a02cf1d26
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; public final class Solution { public static void main(String []args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine()); while(tc-->0) { String tmp[] = br.readLine().split(" "); long n = Long.parseLong(tmp[0]); long k = Long.parseLong(tmp[1]); long a = Long.parseLong(tmp[2]); long b = Long.parseLong(tmp[3]); if(b*k >= n) { System.out.println(-1); continue; } if(a*k < n) { System.out.println(k); continue; } long l = 0, e = k; long ans = -1; while(l<e) { long m = (l+e)/2; if(check(n, k, m, a, b)) { ans = m; l = m+1; } else e = m; } System.out.println(ans); } } public static boolean check(long n, long k, long m, long a, long b) { long v = (a*m)+((k-m)*b); if((long)n-v > 0) return true; else return false; } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
e21df36d9209fa92533b070638ba76af
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
//package learning; import java.util.*; import java.io.*; import java.lang.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Nitslocal { static ArrayList<String> s1; static boolean[] prime; static int n = (int)1e7; static void sieve() { Arrays.fill(prime , true); prime[0] = prime[1] = false; for(int i = 2 ; i * i <= n ; ++i) { if(prime[i]) { for(int k = i * i; k< n ; k+=i) { prime[k] = false; } } } } public static void main(String[] args) { InputReader sc = new InputReader(System.in); prime = new boolean[n + 1]; sieve(); prime[1] = false; int q = sc.ni(); while(q-- > 0) { int k = sc.ni(); int n = sc.ni(); int a = sc.ni(); int b =sc.ni(); int ans = Math.min(n, (k-(b*n)-1)/(a-b)); if((k-1)/b < n) w.println("-1"); else w.println(ans); } w.close(); } static void bfs(int s) { vis[s] = true; Queue<Integer> q = new LinkedList<>(); q.add(s); color[s] = 1; level[s] = 0; p[s] = s; while(q.size()>0) { int cc = q.poll(); //ArrayList<Integer> te= new ArrayList<>(); Iterator itr = hs[cc].iterator(); while(itr.hasNext()) { Integer e = (Integer) itr.next(); //w.print(e + " "); if(!vis[e]) { q.add(e); // te.add(e); p[e] = cc; if(color[cc]==1) color[e] = 2; else color[e] = 1; level[e] = level[cc]+1; vis[e] = true; } } // w.println(); } } static int []level; static int []color; static ArrayList<Integer> []hs; static boolean []vis; static int count = 0; static int []p; //static int [][]arr; static boolean [][]v; //static int [][]l; static boolean con(int []p,int q) { boolean res = false; for(int i=0;i<6;i++) { if(p[i]==q) { res = true; break; } } return res; } static String replace(String s,int a,int n) { char []c = s.toCharArray(); for(int i=1;i<n;i+=2) { int num = (int) (c[i] - 48); num += a; num%=10; c[i] = (char) (num+48); } return new String(c); } static String move(String s,int h,int n) { h%=n; char []c = s.toCharArray(); char []temp = new char[n]; for(int i=0;i<n;i++) { temp[(i+h)%n] = c[i]; } return new String(temp); } public static int ip(String s){ return Integer.parseInt(s); } static class multipliers implements Comparator<Long>{ public int compare(Long a,Long b) { if(a<b) return 1; else if(b<a) return -1; else return 0; } } static class multipliers1 implements Comparator<Student>{ public int compare(Student a,Student b) { if(a.y<b.y) return 1; else if(b.y<a.y) return -1; else { if(a.id < b.id) return 1; else if(b.id<a.id) return -1; else return 0; //return 0; } } } // Java program to generate power set in // lexicographic order. 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 ni() { 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 nl() { 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[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { 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; } } static PrintWriter w = new PrintWriter(System.out); static class Student { int id; //int x; int y; //long z; Student(int id,int y) { this.id = id; //this.x = x; //this.s = s; this.y = y; // this.z = z; } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
69ed7c9cc670d16ae32f41d4517a2f06
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.math.*; public class computergame { public static int com(int k,int n,int a,int b) { int r,s,t; r=s=t=0; if((BigInteger.valueOf(a).multiply(BigInteger.valueOf(n))).compareTo(BigInteger.valueOf(k))<0) return n; else if((BigInteger.valueOf(b).multiply(BigInteger.valueOf(n))).compareTo(BigInteger.valueOf(k))>=0) return -1; else { t=a-b; s=k-(n*b); s--; r=s/t; } return r; } public static void main(String args[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); int i,j,r,result,t; r=0; String a; t=Integer.parseInt(in.readLine()); int[] b=new int[4]; for(j=0;j<t;j++) { a=in.readLine(); a=a+' '; r=0; for(i=0;i<a.length();i++) { if(a.charAt(i)==' ') { b[r++]=Integer.parseInt(a.substring(0,i)); a=a.substring(i+1); i=-1; } } result=com(b[0],b[1],b[2],b[3]); System.out.println(result); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
701485703bb800c9bc4656bd1eaa5448
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in; public static void solve(int q){ while(q-->0){ long k = in.nextLong(); long n=in.nextLong(); long a = in.nextLong(); long b = in.nextLong(); k--; if(n*b>k){//if n games require charge k or more System.out.println(-1); }else{ long jp = (k-(n*b))/(a-b); System.out.println(Math.min(n,jp)); } } /* 1 5 2 3 2 */ } public static void main(String[] args) { in = new Scanner(System.in); int q = in.nextInt(); solve(q); } //while solving this question, before looking at example test cases, I imagined possible consequences and got afraid of it, and therefore didn't solve. //i.e. I gave it up by first impression, without deeper look at it. }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d7deebb66010373bbc11a9d14e88fc3d
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in; public static void solve(int q){ while(q-->0){ long k = in.nextLong(); long n=in.nextLong(); long a = in.nextLong(); long b = in.nextLong(); k--; if(n>k/b){//if n games require charge k or more System.out.println(-1); }else{ long jp = (k-(n*b))/(a-b); System.out.println(Math.min(n,jp)<0?-1:Math.min(n,jp)); } } /* 1 5 2 3 2 1 996876820 939229 661108 2517 */ } public static void main(String[] args) { in = new Scanner(System.in); int q = in.nextInt(); solve(q); } //while solving this question, before looking at example test cases, I imagined possible consequences and got afraid of it, and therefore didn't solve. //i.e. I gave it up by first impression, without deeper look at it. }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d73f6e15cdfc4804cdf048f81c5836a4
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in; public static void solve(int q){ while(q-->0){ long k = in.nextLong(); long n=in.nextLong(); long a = in.nextLong(); long b = in.nextLong(); k--; if(n*b>k){//if n games require charge k or more System.out.println(-1); }else{ long jp = (k-(n*b))/(a-b); System.out.println(Math.min(n,jp)); } } /* 1 5 2 3 2 1 996876820 939229 661108 2517 */ } public static void main(String[] args) { in = new Scanner(System.in); int q = in.nextInt(); solve(q); } //while solving this question, before looking at example test cases, I imagined possible consequences and got afraid of it, and therefore didn't solve. //i.e. I gave it up by first impression, without deeper look at it. }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
68177f4a88e55d458890e18399d2f91a
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in; public static void solve(int q){ while(q-->0){ long k = in.nextLong(); long n=in.nextLong(); long a = in.nextLong(); long b = in.nextLong(); k--; if(n*b > k){//if n games require charge k or more System.out.println(-1); }else{ long jp = (k-(n*b))/(a-b); System.out.println(Math.min(n,jp)); } } /* 1 5 2 3 2 1 996876820 939229 661108 2517 */ } public static void main(String[] args) { in = new Scanner(System.in); int q = in.nextInt(); solve(q); } //while solving this question, before looking at example test cases, I imagined possible consequences and got afraid of it, and therefore didn't solve. //i.e. I gave it up by first impression, without deeper look at it. }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
0ada5296cfabdafc9690e766688d9062
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* abhi2601 */ public class Q1 implements Runnable{ final static long mod = (long)1e9 + 7; static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a,int b){ this.a=a; this.b=b; } public int compareTo(Pair p){ return this.b-p.b; } } public void run(){ InputReader sc = new InputReader(System.in); //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); int q=sc.nextInt(); for(int jj=0;jj<q;jj++){ long k=sc.nextLong(); long n=sc.nextLong(); long a=sc.nextLong(); long b=sc.nextLong(); long ans=-1L; long max=Math.max(0L,(long)Math.ceil((double)(k-a)/a)); long remn=n-max; if(remn<=0){ w.println(n); continue; } long l=0,r=max; while(l<=r){ long mid=l+(r-l)/2L; long t1=k-mid*a; long maxb=(long)Math.ceil((double)(t1-b)/b); //w.println(mid+" "+max+" "+maxb); if(mid+maxb>=n){ ans=Math.max(mid,ans); l=mid+1; } else r=mid-1; } w.println(ans); } w.close(); } static class Comp implements Comparator<String>{ public int compare(String x,String y){ if(x.length()-y.length()==0){ return x.compareTo(y); } return x.length()-y.length(); } } //static PrintWriter w; /*File in=new File("input.txt"); File out=new File("output.txt"); Scanner sc= null; try { sc = new Scanner(in); } catch (FileNotFoundException e) { e.printStackTrace(); } try { w=new PrintWriter(out); } catch (FileNotFoundException e) { e.printStackTrace(); }*/ static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Q1(),"q1",1<<26).start(); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
6d69ee9742f2433857891a7d77dc6130
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* abhi2601 */ public class Q1 implements Runnable{ final static long mod = (long)1e9 + 7; static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a,int b){ this.a=a; this.b=b; } public int compareTo(Pair p){ return this.b-p.b; } } public void run(){ InputReader sc = new InputReader(System.in); //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); int q=sc.nextInt(); for(int jj=0;jj<q;jj++){ long k=sc.nextLong(); long n=sc.nextLong(); long a=sc.nextLong(); long b=sc.nextLong(); long ans=-1L; long l=0,r=n; while(l<=r){ long mid=(l+r)/2; long temp=mid*a+(n-mid)*b; if(temp<k){ ans=mid; l=mid+1; } else r=mid-1; } w.println(ans); } w.close(); } static class Comp implements Comparator<String>{ public int compare(String x,String y){ if(x.length()-y.length()==0){ return x.compareTo(y); } return x.length()-y.length(); } } //static PrintWriter w; /*File in=new File("input.txt"); File out=new File("output.txt"); Scanner sc= null; try { sc = new Scanner(in); } catch (FileNotFoundException e) { e.printStackTrace(); } try { w=new PrintWriter(out); } catch (FileNotFoundException e) { e.printStackTrace(); }*/ static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Q1(),"q1",1<<26).start(); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
76d90b046f557defd2778ca79e10a994
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author revanth */ 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); CComputerGame solver = new CComputerGame(); solver.solve(1, in, out); out.close(); } static class CComputerGame { public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); long k, n, a, b; while (t-- > 0) { k = in.nextInt(); n = in.nextInt(); a = in.nextInt(); b = in.nextInt(); if (k <= n * b) { out.println("-1"); continue; } long l = 0, r = n, m; while (l < r) { m = (l + r + 1) / 2; if (a * m + (n - m) * b < k) l = m; else r = m - 1; } out.println(l); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private InputReader.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 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); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
90989e7c9e791cfe61a94833df6edfaa
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); for (int i = 0; i < q; i++) { long k = scan.nextLong(); long n = scan.nextLong(); long a = scan.nextLong(); long b = scan.nextLong(); k = k - n * b - 1; if (k < 0) { System.out.println(-1); } else { System.out.println(Math.min(k / (a - b), n)); } } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d66ea78139d93b0f0d290c80b956fe6b
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Built using CHelper plug-in Actual solution is at the top */ public class Practice { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int q = in.nextInt(); for (int k = 0; k < q; k++) { long charge = in.nextLong(); long n=in.nextLong(); long a=in.nextLong(); long b=in.nextLong(); out.println(binarySearch(a, b, n, charge)); } } } public static long binarySearch(long a,long b,long n,long charge) { long l = 0, r = n; long ans=-1; while (l <= r) { long m = l + (r - l) / 2; // If x greater, ignore left half if ((a*m)+(b*(n-m))< charge){ l = m + 1; ans=m; } // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was // not present return ans ; } public long GCD(long a, long b) { if (b == 0) { return a; } return GCD(b, a % b); } public static long nCr(int n, int r) { return n * (n - 1) / 2; } 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\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
5434754da0e55c2d7a5b234401160c09
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Main { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception 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 line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); final int MOD = 1000000007; int q = sc.nextInt(); for(int i=0;i<q;i++) { long k = sc.nextLong(), n = sc.nextLong(), a = sc.nextLong(), b = sc.nextLong(); pw.println(k-n*b<=0?-1:Math.min(n,(k-n*b-1)/(a-b))); } pw.close(); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
8b7d59bd3ef4c25a37593d046f63a40b
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; public class Solution {static int mod=1000000007; static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int t=sc.nextInt(); while(t-->0) { long k=sc.nextInt(); long turn=sc.nextInt(); long a=sc.nextInt(); long b=sc.nextInt(); long req=turn*b; long left=k-req; if(left<=0) { System.out.println(-1); continue; } long ex=a-b; // System.out.println(ex+" "+left); long c=0; c=left/ex; long rem=left%ex; if(rem==0) { c--; } if(c<turn) System.out.println(c); else System.out.println(turn); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
5bef08e36dbd7c46e486a86999fac2ee
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ 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(); } static class TaskC { private long battery; private long nMoves; private long a; private long b; private boolean canFinish(long noCharge) { long rem = battery - a * noCharge; if (noCharge == nMoves && rem > 0) return true; if (rem <= b) return false; long need = nMoves - noCharge; return rem - b * need > 0; } public void solve(int testNumber, InputReader in, OutputWriter out) { int q = in.nextInt(); while (q-- > 0) { battery = in.nextInt(); nMoves = in.nextInt(); a = in.nextInt(); b = in.nextInt(); long left = -1, right = nMoves + 1; while (right > left + 1) { long mid = (left + right) / 2; if (canFinish(mid)) { left = mid; } else { right = mid; } } out.println(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 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 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); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
596be60458547a6cf68dc61c55cddd65
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ 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(); } static class TaskC { private int battery; private int nMoves; private int a; private int b; private boolean canFinish(int noCharge) { long rem = battery - (long) a * noCharge; if (noCharge == nMoves && rem > 0) return true; if (rem <= b) return false; int need = nMoves - noCharge; return rem - (long) b * need > 0; } public void solve(int testNumber, InputReader in, OutputWriter out) { int q = in.nextInt(); while (q-- > 0) { battery = in.nextInt(); nMoves = in.nextInt(); a = in.nextInt(); b = in.nextInt(); int left = -1, right = nMoves + 1; while (right > left + 1) { int mid = (left + right) / 2; if (canFinish(mid)) { left = mid; } else { right = mid; } } out.println(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 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 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); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
e458068d4848b2b9faa074732fad4a43
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { FastReader in = new FastReader(); int q = in.nextInt(); for (int i = 0; i < q; i++) { long k = in.nextLong(); int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(); k -= (long)b * n; if (k <= 0) System.out.println(-1); else { int play = (int) k / (a - b); if (k - (a - b) * play == 0) play--; System.out.println(Math.min(n, play)); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n) { int[] array = new int[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] nextSumLongArray(int n) { long[] array = new long[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextSortedLongArray(int n) { long array[] = nextLongArray(n); Arrays.sort(array); return array; } 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
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d72b91eb447a83ef2051f3dd4c026061
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class ComputerGame { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for (int i = 0; i < t; i++) { long k = input.nextLong(); long n = input.nextLong(); long a = input.nextLong(); long b = input.nextLong(); if(b*n>= k) System.out.println(-1); else if(a*n< k) System.out.println(n); else if(a*n == k) System.out.println(n-1); else{ long s = (k-(n*b))/(a-b); long m = (k-(n*b))%(a-b); if(m==0 && s>0) System.out.println(s-1); else System.out.println(s); } } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
8efbf178d2833c5deace22704d73c7cc
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Collections; public class JavaApplication20 { public static void main(String[] args) { FastReader read = new FastReader(); int q = read.nextInt(); for(int i = 0; i<q; i++){ int k = read.nextInt(); int n = read.nextInt(); int a = read.nextInt(); int b = read.nextInt(); if(k/b<n){ System.out.println(-1); continue; } if(k/b == n && k%b==0){ System.out.println(-1); continue; } int lo = 0; int hi = k/a; int mid = (lo+hi)/2; if(hi>n){ System.out.println(n); continue; } while(hi-lo>1){ mid = (lo+hi)/2; if(mid*a + ((n-mid)*b)<k ){ lo = mid; } else{ hi = mid-1; } } if(hi*a + ((n-hi)*b)<k){ System.out.println(hi); } else{ System.out.println(lo); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
9ffd63c4c58c3e6bbdb7f98e7a706083
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class codeforces{ public static void main(String[] args) throws IOException { InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); StringBuilder str=new StringBuilder(); PrintWriter out=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); String[] lol; int[] freq; while(t-->0){ lol=br.readLine().split(" "); long k=Long.parseLong(lol[0]); long n=Long.parseLong(lol[1]); long a=Long.parseLong(lol[2]); long b=Long.parseLong(lol[3]); if(b*n>=k) str.append("-1\n"); else if(a*n<k) str.append(n+"\n"); else { k-=(b*n); a-=b; if(k%a==0) str.append((k/a)-1+"\n"); else str.append((k/a)+"\n"); } } out.print(str); out.close(); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d71f5993c6dfeb0668dd7f86e5db9f5f
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class codeforces{ public static void main(String[] args) throws IOException { InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); StringBuilder str=new StringBuilder(); PrintWriter out=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); String[] lol; int[] freq; while(t-->0){ lol=br.readLine().split(" "); long k = Long.parseLong(lol[0]); long n = Long.parseLong(lol[1]); long a = Long.parseLong(lol[2]); long b = Long.parseLong(lol[3]); if(b*n>=k) str.append("-1\n"); // else // if(a*n+b==k) // str.append((n-1)+"\n"); else if(a*n<k) str.append(n+"\n"); else { long x = (k-(n*b))/(a-b); if((k - (n*b))%(a-b) == 0) { x--; } str.append(x+"\n"); } } out.print(str); out.close(); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
d70e824d01b787594e71df42c3a111d5
train_001.jsonl
1561559700
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Rextester{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = new Integer(br.readLine()); StringBuffer sb = new StringBuffer(); while(t-->0){ StringTokenizer st = new StringTokenizer(br.readLine()); int k = new Integer(st.nextToken()); int n = new Integer(st.nextToken()); int a = new Integer(st.nextToken()); int b = new Integer(st.nextToken()); long c = k - (long)n*a; if(c>0){ sb.append(n).append("\n"); } else{ long increment = a-b; long nu = (1-c)/increment; //System.out.println(nu+" "+increment); if((1-c)%increment>0){ if(nu+1>n){ sb.append("-1").append("\n"); } else{ sb.append(n-(nu+1)).append("\n"); } } else{ if(nu>n){ sb.append("-1").append("\n"); } else{ sb.append(n-nu).append("\n"); } } } } System.out.println(sb); } }
Java
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
3 seconds
["4\n-1\n5\n2\n0\n1"]
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Java 8
standard input
[ "binary search", "math" ]
2005224ffffb90411db3678ac4996f84
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
1,400
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
standard output
PASSED
0d9c22144d866fe0345305903b720900
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.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; public class Main { public static void main(String[] args) { Task mSol = new Task(); mSol.solve(); mSol.flush(); mSol.close(); } } class Task { public FasterScanner mFScanner; public PrintWriter mOut; private int[] mSeq; private int N; public Task() { mFScanner = new FasterScanner(); mOut = new PrintWriter(System.out); } public void solve() { ArrayList<Point> point; int i; int s, t; int s1, s2; int l1, l2; int val1, val2; int countFirst[]; int countSecond[]; int begin; boolean status; int lastNum; point = new ArrayList<Point>(); N = mFScanner.nextInt(); mSeq = new int[N]; countFirst = new int[N]; countSecond = new int[N]; for (i = 0; i < N; i++) mSeq[i] = mFScanner.nextInt() - 1; lastNum = mSeq[N - 1]; if (mSeq[0] == 0) countFirst[0]++; else countSecond[0]++; for (i = 1; i < N; i++) { countFirst[i] = countFirst[i - 1]; countSecond[i] = countSecond[i - 1]; if (mSeq[i] == 0) countFirst[i]++; else countSecond[i]++; } for (t = 1; t <= N; t++) { begin = 0; val1 = val2 = t; s1 = s2 = 0; status = true; while (begin < N) { l1 = lowerBound(countFirst, begin, N - 1, val1); l2 = lowerBound(countSecond, begin, N - 1, val2); if (l1 == N && l2 == N) { status = false; break; } begin = Math.min(l1, l2); val1 = countFirst[begin] + t; val2 = countSecond[begin] + t; begin++; if (l1 < l2) s1++; else s2++; } if (!status || s1 == s2) continue; s = Math.max(s1, s2); if ((s1 == s && lastNum != 0) || (s2 == s && lastNum != 1)) continue; point.add(new Point(s, t)); } Collections.sort(point); mOut.println(point.size()); for (Point p : point) { mOut.print(p.s); mOut.print(" "); mOut.println(p.t); } } public int lowerBound(int[] array, int first, int last, long val) { int count, step, it; count = last - first + 1; while (count > 0) { it = first; step = count / 2; it += step; if (array[it] < val) { first = ++it; count -= step + 1; } else { count = step; } } return first; } class Point implements Comparable<Point> { int s; int t; public Point(int s, int t) { this.s = s; this.t = t; } @Override public int compareTo(Point o) { // TODO Auto-generated method stub int ret = Integer.compare(this.s, o.s); if (ret == 0) return Integer.compare(this.t, o.t); return ret; } } public void flush() { mOut.flush(); } public void close() { mOut.close(); } } class FasterScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { this(System.in); } public FasterScanner(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 nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } }
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
03794b3d4191f7da51985192d07b8980
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.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; public class TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int s = max1 / 2; s >= 1; s--) { int index, t1 = 0, t2 = 0; if (map[s][winner] < map[s][loser] || map[s][loser] == 0) { index = map[s][winner] - 1; t1 = 1; } else { index = map[s][loser] - 1; t2 = 1; } int next1, next2, i1, i2; while (true) { next1 = score[index][winner] + s; next2 = score[index][loser] + s; if (next1 > max1) break; if (next2 > max2) { if ((max1 - score[index][winner]) % s == 0) { t1 += (max1 - score[index][winner]) / s; if (t1 > t2) { Pair p = new Pair(t1, s); int insert = ans.size(); while(insert > 0 && p.t == ans.get(insert-1).t) insert--; ans.add(insert, p); } } break; } i1 = map[next1][winner] - 1; i2 = map[next2][loser] - 1; if (i1 > i2) { t2++; index = i2; } else { // i1 must be < i2. i1 can not be equals to i2 // because any number appears only once in map[x][winner] and map[x][loser] t1++; index = i1; } } } out.println(ans.size()); /* Collections.sort(ans, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.t == o2.t) return o1.s - o2.s; return o1.t - o2.t; } }); */ for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
0dd28239ac397b3c6d82b6dbf62d08f9
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.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; public class TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int i = max1 / 2; i >= 1; i--) { int index, s = 0, t1 = 0, t2 = 0; if (map[i][winner] < map[i][loser] || map[i][loser] == 0) { index = map[i][winner] - 1; s = score[index][winner]; t1 = 1; } else { index = map[i][loser] - 1; s = score[index][loser]; t2 = 1; } int next1, next2, i1, i2; while (true) { next1 = score[index][winner] + s; next2 = score[index][loser] + s; if (next1 > max1) break; if (next2 > max2) { if ((max1 - score[index][winner]) % s == 0) { t1 += (max1 - score[index][winner]) / s; if (t1 > t2) { ans.add(new Pair(t1, s)); } } break; } i1 = map[next1][winner] - 1; i2 = map[next2][loser] - 1; if (i1 > i2) { t2++; index = i2; } else { t1++; index = i1; } } } out.println(ans.size()); Collections.sort(ans, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.t == o2.t) return o1.s - o2.s; return o1.t - o2.t; } }); for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
063942a235902663c46b6b438dbc4a5c
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 TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int i = max1 / 2; i >= 1; i--) { int index, s = 0, t1 = 0, t2 = 0; if (map[i][winner] < map[i][loser] || map[i][loser] == 0) { index = map[i][winner] - 1; s = score[index][winner]; t1 = 1; } else { index = map[i][loser] - 1; s = score[index][loser]; t2 = 1; } while (index < n - 1) { int next1 = score[index][winner] + s; int next2 = score[index][loser] + s; int i1, i2; if (next1 <= max1) { i1 = map[next1][winner] - 1; } else { break; } if (next2 > max2) { if ((max1 - score[index][winner]) % s == 0) { t1 += (max1 - score[index][winner]) / s; if (t1 > t2) { ans.add(new Pair(t1, s)); } } break; } i2 = map[next2][loser] - 1; if (i1 > i2) { t2++; index = i2; } else if (i1 < i2) { t1++; index = i1; if (i1 == n - 1 && t1 > t2) { ans.add(new Pair(t1, s)); break; } } else { break; } } } out.println(ans.size()); Collections.sort(ans, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.t == o2.t) return o1.s - o2.s; return o1.t - o2.t; } }); for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
a5de51a162cc71b58614cc1344b2b37f
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.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; public class TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int s = max1 / 2; s >= 1; s--) { int index, t1 = 0, t2 = 0; if (map[s][winner] < map[s][loser] || map[s][loser] == 0) { index = map[s][winner] - 1; t1 = 1; } else { index = map[s][loser] - 1; t2 = 1; } int next1, next2, i1, i2; while (true) { next1 = score[index][winner] + s; next2 = score[index][loser] + s; if (next1 > max1) break; if (next2 > max2) { if ((max1 - score[index][winner]) % s == 0) { t1 += (max1 - score[index][winner]) / s; if (t1 > t2) { Pair p = new Pair(t1, s); int insert = ans.size(); while(insert > 0 && p.t == ans.get(insert-1).t) insert--; ans.add(insert, new Pair(t1, s)); } } break; } i1 = map[next1][winner] - 1; i2 = map[next2][loser] - 1; if (i1 > i2) { t2++; index = i2; } else { t1++; index = i1; } } } out.println(ans.size()); for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
0e3fe5f69d0b271709e37c06fc95c73b
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 TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int i = max1 / 2; i >= 1; i--) { int index, s = 0, t1 = 0, t2 = 0; if (map[i][winner] < map[i][loser] || map[i][loser] == 0) { index = map[i][winner] - 1; s = score[index][winner]; t1 = 1; } else { index = map[i][loser] - 1; s = score[index][loser]; t2 = 1; } while (index < n - 1) { int next1 = score[index][winner] + s; int next2 = score[index][loser] + s; int i1, i2; if (next1 <= max1) { i1 = map[next1][winner] - 1; } else { break; } i2 = next2 <= max2 ? map[next2][loser] - 1 : n; if (i1 > i2) { t2++; index = i2; } else if (i1 < i2) { t1++; index = i1; if (i1 == n - 1 && t1 > t2) { ans.add(new Pair(t1, s)); break; } } else { break; } } } out.println(ans.size()); Collections.sort(ans, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.t == o2.t) return o1.s - o2.s; return o1.t - o2.t; } }); for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
22ea964f71fa2a0f3c4dbe9c8221649f
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 TennisGame496D { static class Pair { int s, t; public Pair(int t, int s) { this.t = t; this.s = s; } } static void go() { int n = in.nextInt(); int[] a = in.nextIntArray(n); //long start = System.currentTimeMillis(); /* int n = 100000; int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = 1; */ int[][] score = new int[n][2]; int[][] map = new int[100001][2]; int winner = a[n - 1] - 1; int loser = 1 - winner; score[0][a[0] - 1] = 1; map[1][a[0] - 1] = 1; for (int i = 1; i < n; i++) { int j = a[i] - 1; score[i][j] = score[i - 1][j] + 1; map[score[i][j]][j] = i + 1; score[i][1 - j] = score[i - 1][1 - j]; } ArrayList<Pair> ans = new ArrayList<>(); int max1 = score[n - 1][winner], max2 = score[n - 1][loser]; if (max1 > max2) { ans.add(new Pair(1, max1)); } for (int i = max1 / 2; i >= 1; i--) { int index, s = 0, t1 = 0, t2 = 0; if (map[i][winner] < map[i][loser] || map[i][loser] == 0) { index = map[i][winner] - 1; s = score[index][winner]; t1 = 1; } else { index = map[i][loser] - 1; s = score[index][loser]; t2 = 1; } while (true) { int next1 = score[index][winner] + s; int next2 = score[index][loser] + s; int i1, i2; if (next1 <= max1) { i1 = map[next1][winner] - 1; } else { break; } if (next2 > max2) { if ((max1 - score[index][winner]) % s == 0) { t1 += (max1 - score[index][winner]) / s; if (t1 > t2) { ans.add(new Pair(t1, s)); } } break; } i2 = map[next2][loser] - 1; if (i1 > i2) { t2++; index = i2; } else if (i1 < i2) { t1++; index = i1; } else { break; } } } out.println(ans.size()); Collections.sort(ans, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.t == o2.t) return o1.s - o2.s; return o1.t - o2.t; } }); for (int i = 0; i < ans.size(); i++) { out.println(ans.get(i).t + " " + ans.get(i).s); } } static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); go(); out.close(); } static 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[] nextIntArray(int len) { int[] ret = new int[len]; for (int i = 0; i < len; i++) ret[i] = nextInt(); return ret; } public long[] nextLongArray(int len) { long[] ret = new long[len]; for (int i = 0; i < len; i++) ret[i] = nextLong(); return ret; } public int nextInt() { return (int) nextLong(); } 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 String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder sb = new StringBuilder(1024); do { sb.append((char) c); c = read(); } while (!isSpaceChar(c)); return sb.toString(); } public static boolean isSpaceChar(int c) { switch (c) { case -1: case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } } }
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
62a35a203a3bc4ea4eedfdc839373c84
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 Main implements Runnable { class Res{ int s, t; Res(int s, int t){this.s = s; this.t = t;} } public void solve() throws IOException { int N = nextInt(); int[] a = new int[N]; for(int i = 0; i < N; i++) a[i] = nextInt(); int[] first = new int[N+1]; int[] second = new int[N+1]; for(int i = 0;i < N; i++){ if(a[i] == 1) first[i+1] = first[i] + 1; else first[i+1] = first[i]; if(a[i] == 2) second[i+1] = second[i] + 1; else second[i+1] = second[i]; } // debug(first); // debug(second); ArrayList<Res> al = new ArrayList<>(); outer: for(int t = 1; t <= N; t++){ int wins0 = 0, wins1 = 0; int ptr = 0; int last = -1; while(ptr < N){ int firstAt = search(first[ptr] + t, first); int secondAt = search(second[ptr] + t, second); // System.out.println(" " + t + " " +firstAt + " " + secondAt); int min = Math.min(firstAt, secondAt); if(min > N){ continue outer; } if(firstAt < secondAt){ wins0++; ptr = firstAt; last = 0; } else{ wins1++; ptr = secondAt; last = 1; } } if(wins0 != wins1){ if(wins0 > wins1 && last == 0) al.add(new Res(wins0, t)); else if(wins1 > wins0 && last == 1) al.add(new Res(wins1, t)); } } Collections.sort(al, new Comparator<Res>(){ public int compare(Res a, Res b){ int T = a.s - b.s; if(T == 0) T = a.t - b.t; return T; } }); out.println(al.size()); for(Res r : al)out.println(r.s + " " + r.t); } public int search(int value, int[] a){ int lo = 0, hi = a.length; while(hi - lo > 1){ int mid = (lo + hi) / 2; if(a[mid] >= value) hi = mid; else lo = mid; } return hi; } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
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
276f039e4cb027b94f98e4a828383b26
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.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; /*from collections import Counter from collections import Counter def solve(lst): ones = _count(lst, 1) twos = _count(lst, 2) counter = Counter(lst) if counter[1] == counter[2]: return [] winner, T = counter.most_common(1)[0] result = [] for t in range(1, T + 1): possible, s = _is_set_possible(lst, ones, twos, t) if possible: result.append((s, t)) return sorted(result) def _is_set_possible(lst, ones, twos, t): one_won = two_won = 0 winner_ind = next_winner(ones, twos, 0, t) possible = False while winner_ind != -1: winner = lst[winner_ind - 1] one_won += winner == 1 two_won += winner == 2 if winner_ind == len(lst): if winner == 1 and one_won > two_won: possible = True elif winner == 2 and two_won > one_won: possible = True winner_ind = next_winner(ones, twos, winner_ind, t) return (possible, max(one_won, two_won)) def _count(lst, target): result = [0] for i, e in enumerate(lst): last = result[-1] result.append(last + (e == target)) return result def next_winner(ones, twos, ind, t): o = _next_winner(ones, ind, t) t = _next_winner(twos, ind, t) if o == -1 or t == -1: return max(o, t) else: return min(o, t) def _next_winner(lst, i, t): cur = lst[i] target = cur + t return binary_search(lst, target=target, lo=i, hi=len(lst) - 1) def binary_search(lst, target, lo, hi): if lo > hi: return -1 mid = (lo + hi) // 2 if lst[mid] == target and (mid == 0 or lst[mid - 1] != target): return mid elif lst[mid] < target: return binary_search(lst, target, mid + 1, hi) else: return binary_search(lst, target, lo, mid - 1) */ public class Foo { public static class Tuple<X, Y> { public final X x; public final Y y; public Tuple(X x, Y y) { this.x = x; this.y = y; } } @SuppressWarnings("unchecked") static List<Tuple<Integer, Integer>> solve(int[] lst) { List<Tuple<Integer, Integer>> result = new ArrayList<Tuple<Integer, Integer>>(); int[] ones = count(lst, 1); int[] twos = count(lst, 2); int oneLast = ones[ones.length - 1]; int twoLast = twos[twos.length - 1]; int t, T; if (oneLast == twoLast) { return result; } else if (oneLast > twoLast) { T = oneLast; } else { T = twoLast; } for (t=1; t<=T; t++) { int possible = isSetPossible(lst, ones, twos, t); if (possible != -1) { @SuppressWarnings("rawtypes") Tuple tuple = new Foo.Tuple(possible, t); result.add(tuple); } } Collections.sort(result, new Comparator<Tuple<Integer, Integer>>() { public int compare(Tuple<Integer, Integer> t0, Tuple<Integer, Integer> t1) { if (t0.x < t1.x) { return -1; } else if (t1.x < t0.x) { return 1; } if (t0.y < t1.y) { return -1; } else if (t1.y < t0.y) { return 1; } return 0; } }); return result; } public static int nextWinner(int[] ones, int[] twos, int ind, int t) { int one = _nextWinner(ones, ind, t); int two = _nextWinner(twos, ind, t); if (one == -1 && two == -1) { return -1; } else if (one == -1) { return two; } else if (two == -1) { return one; } else { return Math.min(one, two); } } public static int isSetPossible(int[] lst, int[] ones, int[] twos, int t) { int oneWon = 0; int twoWon = 0; boolean possible = false; int winnerInd = nextWinner(ones, twos, 0, t); while (winnerInd != -1) { int winner = lst[winnerInd - 1]; oneWon += winner == 1? 1 : 0; twoWon += winner == 2? 1 : 0; if (winnerInd == lst.length) { if (winner == 1 && oneWon > twoWon) { possible = true; break; } else if (winner == 2 && twoWon > oneWon) { possible = true; break; } } winnerInd = nextWinner(ones, twos, winnerInd, t); } if (possible) { return Math.max(oneWon, twoWon); } else { return -1; } } public static int _nextWinner(int[] lst, int i, int t) { int target = lst[i] + t; return find(lst, target, i + t, lst.length - 1); } public static int[] count(int lst[], int t) { int length = lst.length; int result[] = new int[length + 1]; result[0] = 0; for (int i = 1; i <= length; i++) { int last = result[i - 1]; if (lst[i - 1] == t) { result[i] = last + 1; } else { result[i] = last; } } return result; } public static int find(int lst[], int t, int lo, int hi) { while (lo <= hi) { int mid = (lo + hi) / 2; if (lst[mid] == t && (mid == 0 || lst[mid - 1] != t)) { return mid; } else if (lst[mid] < t) { lo = mid + 1; } else { hi = mid - 1; } } return -1; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] lst = new int[n]; sc.nextLine(); String[] s = sc.nextLine().split(" "); for (int i = 0; i < n; i++) { lst[i] = Integer.parseInt(s[i]); } List<Tuple<Integer, Integer>> result = solve(lst); System.out.println(result.size()); for (Tuple<Integer, Integer> t : result) { System.out.println(String.format("%s %s", t.x, t.y)); } } }
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
99186cabd5d25131d761fe3db0d9cf49
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 { void bf(int[] a) { int cm = 0, n = a.length; for(int p = 1; p <= n; ++p) { int s = 0, x = 0, y = 0, xs = 0, ys = 0; for(int i = 0; i < n; ++i) { if(a[i] == 1) { x += 1; } else { y += 1; } if(x == p) { xs += 1; x = 0; y = 0; } else if(y == p) { ys += 1; x = 0; y = 0; } ++cm; } if(x + y == 0) debug(p, Math.max(xs, ys)); } debug(cm, n); } 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(lo == n && ys == n) return -1; 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