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
sequencelengths
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
02f916697550b1eeaa008a8e0a4597f3
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.concurrent.*; @SuppressWarnings("unchecked") public class P79B { final static String [] fruits = {"Carrots", "Kiwis", "Grapes"}; public void run() throws Exception { int n = nextInt(); int m = nextInt(); int k = nextInt(); int t = nextInt(); ArrayList<Integer> w = new ArrayList<Integer>(); for (int i = 0; i < k; i++) { int y = nextInt() - 1; int x = nextInt() - 1; w.add(y * m + x); } Collections.sort(w); for (int i = 0; i < t; i++) { int xy = (nextInt() - 1) * m + nextInt() - 1; int idx = Collections.binarySearch(w, xy); println((idx >= 0) ? "Waste" : fruits[(xy - (-idx - 1)) % fruits.length]); } } // --------------------------------------------------------------------------------------------- public static void main(String... args) { try { new P79B().run(); } catch (Exception e) { System.err.println(e); } finally { pw.close(); } } final static String inFile = null; final static String outFile = null; static InputStream is = null; static OutputStream os = null; static { try { is = (( inFile == null) ? System.in : new FileInputStream( inFile)); os = ((outFile == null) ? System.out : new FileOutputStream(outFile)); } catch (Exception e) { System.err.println(e); } } final static BufferedReader br = new BufferedReader(new InputStreamReader(is)); final static PrintWriter pw = new PrintWriter( new BufferedOutputStream(os)); static StringTokenizer strTok = null; static String token() throws IOException { while ((strTok == null) || (!strTok.hasMoreTokens())) { strTok = new StringTokenizer(br.readLine()); } return (strTok.nextToken()); } void print( char c) { print(c + ""); } void print( long l) { print(l + ""); } void print(double d) { print(d + ""); } void print(Object o) { print(o + ""); } void printsp( char c) { print(c + " "); } void printsp( long l) { print(l + " "); } void printsp(double d) { print(d + " "); } void printsp(Object o) { print(o + " "); } void printsp(String s) { print(s + " "); } void println( char c) { print(c + "\n"); } void println( long l) { print(l + "\n"); } void println(double d) { print(d + "\n"); } void println(Object o) { print(o + "\n"); } void println(String s) { print(s + "\n"); } void println() { pw.println(); } void print(String s) { pw.print(s); } int nextInt() throws Exception { return Integer.valueOf(token()); } long nextLong() throws Exception { return Long.valueOf(token()); } double nextDouble() throws Exception { return Double.valueOf(token()); } String next() throws Exception { return token(); } String nextLine() throws Exception { return br.readLine(); } int [] nextInt(int size) throws Exception { int [] arr = new int [size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } long [] nextLong(int size) throws Exception { long [] arr = new long [size]; for (int i = 0; i < size; i++) arr[i] = nextLong(); return arr; } double [] nextDouble(int size) throws Exception { double [] arr = new double [size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } String [] next(int size) throws Exception { String [] arr = new String [size]; for (int i = 0; i < size; i++) arr[i] = next(); return arr; } String [] nextLines(int size) throws Exception { String [] arr = new String [size]; for (int i = 0; i < size; i++) arr[i] = nextLine(); return arr; } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
147fa731519b4b7af9aa27050fb1de71
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.concurrent.*; @SuppressWarnings("unchecked") public class P79B { final static String [] fruits = {"Carrots", "Kiwis", "Grapes"}; public void run() throws Exception { int n = nextInt(); int m = nextInt(); int k = nextInt(); int t = nextInt(); ArrayList<Integer> w = new ArrayList<Integer>(); for (int i = 0; i < k; i++) { w.add((nextInt() - 1) * m + (nextInt() - 1)); } Collections.sort(w); for (int i = 0; i < t; i++) { int xy = (nextInt() - 1) * m + nextInt() - 1; int idx = Collections.binarySearch(w, xy); println((idx >= 0) ? "Waste" : fruits[(xy - (-idx - 1)) % fruits.length]); } } // --------------------------------------------------------------------------------------------- public static void main(String... args) { try { new P79B().run(); } catch (Exception e) { System.err.println(e); } finally { pw.close(); } } final static String inFile = null; final static String outFile = null; static InputStream is = null; static OutputStream os = null; static { try { is = (( inFile == null) ? System.in : new FileInputStream( inFile)); os = ((outFile == null) ? System.out : new FileOutputStream(outFile)); } catch (Exception e) { System.err.println(e); } } final static BufferedReader br = new BufferedReader(new InputStreamReader(is)); final static PrintWriter pw = new PrintWriter( new BufferedOutputStream(os)); static StringTokenizer strTok = null; static String token() throws IOException { while ((strTok == null) || (!strTok.hasMoreTokens())) { strTok = new StringTokenizer(br.readLine()); } return (strTok.nextToken()); } void print( char c) { print(c + ""); } void print( long l) { print(l + ""); } void print(double d) { print(d + ""); } void print(Object o) { print(o + ""); } void printsp( char c) { print(c + " "); } void printsp( long l) { print(l + " "); } void printsp(double d) { print(d + " "); } void printsp(Object o) { print(o + " "); } void printsp(String s) { print(s + " "); } void println( char c) { print(c + "\n"); } void println( long l) { print(l + "\n"); } void println(double d) { print(d + "\n"); } void println(Object o) { print(o + "\n"); } void println(String s) { print(s + "\n"); } void println() { pw.println(); } void print(String s) { pw.print(s); } int nextInt() throws Exception { return Integer.valueOf(token()); } long nextLong() throws Exception { return Long.valueOf(token()); } double nextDouble() throws Exception { return Double.valueOf(token()); } String next() throws Exception { return token(); } String nextLine() throws Exception { return br.readLine(); } int [] nextInt(int size) throws Exception { int [] arr = new int [size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } long [] nextLong(int size) throws Exception { long [] arr = new long [size]; for (int i = 0; i < size; i++) arr[i] = nextLong(); return arr; } double [] nextDouble(int size) throws Exception { double [] arr = new double [size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } String [] next(int size) throws Exception { String [] arr = new String [size]; for (int i = 0; i < size; i++) arr[i] = next(); return arr; } String [] nextLines(int size) throws Exception { String [] arr = new String [size]; for (int i = 0; i < size; i++) arr[i] = nextLine(); return arr; } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
968bb91ebc4cc717987a866b0ddb0bdd
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
/* * @Author: steve * @Date: 2015-04-07 22:59:22 * @Last Modified by: steve * @Last Modified time: 2015-04-07 23:41:09 */ import java.io.*; import java.util.*; public class ColorfulField { public static void main(String[] args) throws Exception{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); String[] cads=entrada.readLine().split(" "); int n=Integer.parseInt(cads[0]),m=Integer.parseInt(cads[1]),k=Integer.parseInt(cads[2]),t=Integer.parseInt(cads[3]); long[] acu = new long[k]; int cont=0; for(int i=0;i<k;i++){ cads=entrada.readLine().split(" "); int r=Integer.parseInt(cads[0])-1,c=Integer.parseInt(cads[1])-1; acu[cont++]=(r*m)+c; } Arrays.sort(acu); for(int i=0;i<t;i++){ cads=entrada.readLine().split(" "); int r=Integer.parseInt(cads[0])-1,c=Integer.parseInt(cads[1])-1; long pos=(r*m)+c; int llevo=0; for(int j=0;j<k;j++){ if(acu[j]>pos) break; llevo++; } if(llevo>0 && acu[llevo-1]==pos){ System.out.println("Waste"); continue; } pos=pos-llevo; int op=(int)pos%3; switch(op){ case 0: System.out.println("Carrots"); break; case 1: System.out.println("Kiwis"); break; case 2: System.out.println("Grapes"); break; } } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
e212cfd080839d4586c5412414da3973
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; import sun.misc.Queue; /** * * @author Mojtaba */ public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); //String str = reader.readLine(); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); int k = Integer.parseInt(tokenizer.nextToken()); int q = Integer.parseInt(tokenizer.nextToken()); ArrayList<Integer> wasted = new ArrayList<>(); for (int i = 0; i < k; i++) { tokenizer = new StringTokenizer(reader.readLine()); int row = Integer.parseInt(tokenizer.nextToken()) - 1; int column = Integer.parseInt(tokenizer.nextToken()) - 1; wasted.add(row * m + column); } Collections.sort(wasted); for (int i = 0; i < q; i++) { tokenizer = new StringTokenizer(reader.readLine()); int row = Integer.parseInt(tokenizer.nextToken()) - 1; int column = Integer.parseInt(tokenizer.nextToken()) - 1; int f2 = F2(wasted, row * m + column); sb.append(f2 == -1 ? F(-1) : F(((row * m + column - f2)) % 3)).append("\n"); } writer.println(sb.toString().trim()); writer.close(); reader.close(); } private static String F(int i) { switch (i) { case -1: return "Waste"; case 0: return "Carrots"; case 1: return "Kiwis"; case 2: return "Grapes"; } return "Error"; } private static int F2(ArrayList<Integer> wasted, int h) { for (int i = 0; i < wasted.size(); i++) { if (h < wasted.get(i)) { return i; } if (h == wasted.get(i)) { return -1; } } return wasted.size(); } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
f96887d14abb0b10aa989feadd44a9ec
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.util.*; import java.io.*; public class zanah{ public static void main(String args[]) throws IOException{ BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String tmp[] = lector.readLine().split(" "); int a = Integer.parseInt(tmp[0]); int b = Integer.parseInt(tmp[1]); int c = Integer.parseInt(tmp[2]); int d = Integer.parseInt(tmp[3]); int cod[] = new int[c]; HashSet<Integer> tal = new HashSet<Integer>(); for(int n = 0;n<c;n++){ String t = lector.readLine(); int aa = Integer.parseInt(t.substring(0,t.indexOf(" ")))-1; int bb = Integer.parseInt(t.substring(t.indexOf(" ")+1))-1; cod[n] = b*aa+bb; tal.add(cod[n]); } Arrays.sort(cod); StringBuilder sb = new StringBuilder(""); String res[] = {"Carrots","Kiwis","Grapes"}; for(int n = 0;n<d;n++){ String t = lector.readLine(); int aa = Integer.parseInt(t.substring(0,t.indexOf(" ")))-1; int bb = Integer.parseInt(t.substring(t.indexOf(" ")+1))-1; int cc = b*aa+bb; if(tal.contains(cc)) sb.append("Waste\n"); else{ int lo = 0,hi = c-1; while(lo<=hi){ int mid= (lo+hi)/2; if(cc<cod[mid]) hi = mid-1; else lo = mid+1; } //System.out.println("->"+lo); sb.append(res[(cc-lo)%3]+"\n"); } } System.out.print(sb); } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
12b25a01a0701889f1a7bfa801de116d
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
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 m = sc.nextInt(); int k = sc.nextInt(); int t = sc.nextInt(); int[][] waste = new int[k][2]; for (int i = 0; i < k; i++) waste[i] = new int[] { sc.nextInt(), sc.nextInt() }; String[] res = new String[] { "Carrots", "Kiwis", "Grapes" }; while (t-- != 0) { int i = sc.nextInt(); int j = sc.nextInt(); int ind = (i - 1) * m + j - 1; for (int u = 0; u < k; u++) { if (waste[u][0] < i) ind--; else if (waste[u][0] == i && waste[u][1] <= j) ind--; if (waste[u][0] == i && waste[u][1] == j) ind = -1; } if (ind >= 0) System.out.println(res[ind % 3]); else System.out.println("Waste"); } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
5c17e931d3a7d0d32e08c814e947c6aa
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class CodeC { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } 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 int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for(int i = 0; i < n; i++) vals[i] = next(); return vals; } Integer nextInteger() { String s = next(); if(s == null) return null; return Integer.parseInt(s); } int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for(int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } static <T> T fill(T arreglo, int val) { if(arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for(Object x : a) fill(x, val); } else if(arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if(arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if(arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } <T> T[] nextObjectArray(Class <T> clazz, int size) { @SuppressWarnings("unchecked") T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size); for(int c = 0; c < 3; c++) { Constructor <T> constructor; try { if(c == 0) constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE); else if(c == 1) constructor = clazz.getDeclaredConstructor(Scanner.class); else constructor = clazz.getDeclaredConstructor(); } catch(Exception e) { continue; } try { for(int i = 0; i < result.length; i++) { if(c == 0) result[i] = constructor.newInstance(this, i); else if(c == 1) result[i] = constructor.newInstance(this); else result[i] = constructor.newInstance(); } } catch(Exception e) { throw new RuntimeException(e); } return result; } throw new RuntimeException("Constructor not found"); } } static int m; static class Bucket { ArrayList <Integer> entradasO = new ArrayList <Integer> (); TreeMap <Integer, Integer> entradas = new TreeMap <Integer, Integer> (); void close() { Collections.sort(entradasO); for(int i = 0; i < entradasO.size(); i++) entradas.put(entradasO.get(i), i + 1); } int rank(int i) { Map.Entry <Integer, Integer> e = entradas.floorEntry(i); if(e == null) return i; else return i - e.getValue(); } int cuenta() { return m - entradas.size(); } } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); m = sc.nextInt(); Bucket[] buckets = sc.nextObjectArray(Bucket.class, n); int[] suma = new int[n]; int k = sc.nextInt(); int t = sc.nextInt(); for(int i = 0; i < k; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt(); buckets[a].entradasO.add(b); } for(int i = 0; i < n; i++) { buckets[i].close(); suma[i] = (i == 0 ? 0 : suma[i - 1]) + buckets[i].cuenta(); } for(int i = 0; i < t; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt(); if(buckets[a].entradas.containsKey(b)) System.out.println("Waste"); else { int sumaHasta = (a == 0 ? 0 : suma[a - 1]) + buckets[a].rank(b); sumaHasta--; if(sumaHasta % 3 == 0) System.out.println("Carrots"); else if(sumaHasta % 3 == 1) System.out.println("Kiwis"); else System.out.println("Grapes"); } } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
87bd20e2c5ef9523951b013babc10d78
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.*; import java.util.*; public class ColorfulField { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[][] waste = new int[n][]; int[] c = new int[n]; String[] crops = {"Carrots", "Kiwis", "Grapes"}; int[] wastex = new int[k]; int[] wastey = new int[k]; for (int i = 0; i < k; i++) { st = new StringTokenizer(f.readLine()); wastex[i] = Integer.parseInt(st.nextToken())-1; wastey[i] = Integer.parseInt(st.nextToken())-1; c[wastex[i]]++; } int[] d = new int[n]; d[0] = 0; for (int i = 1; i < n; i++) d[i] = d[i-1] + m - c[i-1]; for (int i = 0; i < n; i++) waste[i] = new int[c[i]]; for (int i = 0; i < k; i++) { c[wastex[i]]--; waste[wastex[i]][c[wastex[i]]] = wastey[i]; } for (int i = 0; i < n; i++) Arrays.sort(waste[i]); for (int i = 0; i < t; i++) { st = new StringTokenizer(f.readLine()); int x = Integer.parseInt(st.nextToken())-1; int y = Integer.parseInt(st.nextToken())-1; int num = 0; while (num < waste[x].length && y > waste[x][num]) num++; if (num < waste[x].length && y == waste[x][num]) System.out.println("Waste"); else { int count = d[x]; count += y - num; System.out.println(crops[count%3]); } } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
ee10eaef548d33804e00beda073630ab
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.FileReader; import java.util.Arrays; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author unnamed */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), t = in.nextInt(); Pair[] r = new Pair[k]; int[] qi = new int[t], qj = new int[t]; for (int i = 0; i < k; ++i) r[i] = new Pair(in.nextInt(), in.nextInt()); for (int i = 0; i < t; ++i) { qi[i] = in.nextInt(); qj[i] = in.nextInt(); } String[] word = new String[]{"Carrots", "Kiwis", "Grapes"}; Arrays.sort(r); for (int i = 0; i < t; ++i) { int cnt = 0; boolean waste = false; for (int j = 0; j < k; ++j) if (r[j].i == qi[i] & r[j].j == qj[i]) { waste = true; break; } else if (r[j].i < qi[i] | (r[j].i == qi[i] & r[j].j <= qj[i])) ++cnt; out.println(waste ? "Waste" : word[((qi[i] - 1) * m + qj[i] - 1 - cnt) % 3]); } } public class Pair implements Comparable<Pair> { public int i, j; public Pair(int i, int j) { this.i = i; this.j = j; } public int compareTo(Pair o) { if (this.i != o.i) return this.i - o.i; else return this.j - o.j; } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } 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
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
dfbadcb121dc03db8c80e024f9741d8f
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.FileReader; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author unnamed */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), t = in.nextInt(); int[] ri = new int[k], rj = new int[k], qi = new int[t], qj = new int[t]; for (int i = 0; i < k; ++i) { ri[i] = in.nextInt(); rj[i] = in.nextInt(); } for (int i = 0; i < t; ++i) { qi[i] = in.nextInt(); qj[i] = in.nextInt(); } String[] word = new String[]{"Carrots", "Kiwis", "Grapes"}; for (int i = 0; i < t; ++i) { int cnt = 0; boolean waste = false; for (int j = 0; j < k; ++j) if (ri[j] == qi[i] & rj[j] == qj[i]) { waste = true; break; } else if (ri[j] < qi[i] | (ri[j] == qi[i] & rj[j] <= qj[i])) ++cnt; out.println(waste ? "Waste" : word[((qi[i] - 1) * m + qj[i] - 1 - cnt) % 3]); } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } 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
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
4e6ba248a468da2c54cc96c4a1118099
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.FileReader; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author unnamed */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), t = in.nextInt(); Pair[] r = new Pair[k]; int[] qi = new int[t], qj = new int[t]; for (int i = 0; i < k; ++i) r[i] = new Pair(in.nextInt(), in.nextInt()); for (int i = 0; i < t; ++i) { qi[i] = in.nextInt(); qj[i] = in.nextInt(); } String[] word = new String[]{"Carrots", "Kiwis", "Grapes"}; for (int i = 0; i < t; ++i) { int cnt = 0; boolean waste = false; for (int j = 0; j < k; ++j) if (r[j].i == qi[i] & r[j].j == qj[i]) { waste = true; break; } else if (r[j].i < qi[i] | (r[j].i == qi[i] & r[j].j <= qj[i])) ++cnt; out.println(waste ? "Waste" : word[((qi[i] - 1) * m + qj[i] - 1 - cnt) % 3]); } } public class Pair implements Comparable<Pair> { public int i, j; public Pair(int i, int j) { this.i = i; this.j = j; } public int compareTo(Pair o) { if (this.i != o.i) return this.i - o.i; else return this.j - o.j; } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } 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
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
29121abaff495dc0d915b347b8618af9
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.*; import java.util.*; public class test { public static void main(String[] args) { new test().run(); } void run() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int t = in.nextInt(); HashSet<Integer> hs = new HashSet<Integer>(); for (int i = 0; i < k; i++) hs.add((in.nextInt() - 1) * m + in.nextInt() - 1); for (int i = 0; i < t; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (hs.contains(x * m + y)) out.println("Waste"); else { int total = 0; int num = x * m + y; Iterator<Integer> it = hs.iterator(); while (it.hasNext()) { int a = it.next(); if (a < num) total++; } num -= total; num %= 3; switch (num) { case 0: out.println("Carrots"); break; case 1: out.println("Kiwis"); break; case 2: out.println("Grapes"); break; } } } out.close(); } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
1571ee55c32d97da05c605fd9b83efcb
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int t = in.nextInt(); long [] wasted = new long[k]; int i; int row, col; for(i = 0; i < k; ++i) { row = in.nextInt(); col = in.nextInt(); wasted[i] = m * (row -1) + (col -1); } Arrays.sort(wasted); for(i = 0; i < t; ++i) { row = in.nextInt(); col = in.nextInt(); long cellNumber = (int) m * (row -1) + (col -1); int index = 0; while (index < k) { if (wasted[index] < cellNumber) ++index; else break; } if (index < wasted.length && wasted[index] == cellNumber) System.out.println("Waste"); else { if (index < wasted.length -1 && cellNumber > wasted[index]) index++; int type = (int) (cellNumber - index) % 3; switch (type) { case 0: System.out.println("Carrots"); break; case 1: System.out.println("Kiwis"); break; case 2: System.out.println("Grapes"); break; default: System.out.println("Waste"); break; } } } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
a6b9fd05ecaa18765eebe3c858589b2d
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.*; import java.util.*; public final class colorful_field { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static final String s1="Waste",s2="Grapes",s3="Carrots",s4="Kiwis"; public static void main(String args[]) throws Exception { int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(),q=sc.nextInt(); long[] a=new long[k]; for(int i=0;i<k;i++) { int a1=sc.nextInt(),b1=sc.nextInt(); a[i]=((a1-1)*m)+b1; } Arrays.sort(a); //out.println(Arrays.toString(a)); while(q>0) { int u=sc.nextInt(),v=sc.nextInt(); long r=((u-1)*m)+v; int pos=Arrays.binarySearch(a,r); if(pos>=0) { out.println(s1); q--; continue; } pos++; pos*=-1; r-=pos; r%=3; if(r==0) { out.println(s2); } else if(r==1) { out.println(s3); } else { out.println(s4); } q--; } out.close(); } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
5dc003e6eaf506bc043e8af69409e5aa
train_000.jsonl
1304175600
Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.StringTokenizer; public class Task { private static final boolean readFromFile = false; public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FileOutputStream fileOutputStream; FileInputStream fileInputStream; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File("input.txt")); fileOutputStream = new FileOutputStream(new File("output.txt")); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in,out); s.solve(); out.close(); } } class Solver{ InputReader in; PrintWriter out; public void solve(){ int n=in.nextInt(); int m=in.nextInt(); int k=in.nextInt(); int t=in.nextInt(); int Count[] = new int[n+1]; int Head[] = new int[n+1]; int Next[] = new int[k]; int T[] = new int[k]; Arrays.fill(Head, -1); for (int i=0;i<k;i++){ int y=in.nextInt(); int x=in.nextInt(); Next[i]=Head[y]; Head[y]=i; T[i]=x; Count[y]++; } for (int i=1;i<=n;i++) Count[i]=m-Count[i]; for (int i=0;i<t;i++){ int y=in.nextInt(); int x=in.nextInt(); int pos = x; boolean isLife = true; int j = Head[y]; while (j!=-1){ if (T[j]==x){ isLife=false; break; }else if (T[j]<x) pos--; j=Next[j]; } for (j=1;j<y;j++) pos+=Count[j]; if (!isLife) out.println("Waste"); else switch (pos%3){ case 0: out.println("Grapes");break; case 1: out.println("Carrots");break; case 2: out.println("Kiwis");break; } } } Solver(InputReader in, PrintWriter out){ this.in=in; this.out=out; } } class InputReader{ private BufferedReader buf; private StringTokenizer tok; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.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()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
Java
["4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1"]
2 seconds
["Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots"]
NoteThe sample corresponds to the figure in the statement.
Java 7
standard input
[ "implementation", "sortings" ]
bfef3f835357dae290620efabe650580
In the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).
1,400
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
standard output
PASSED
1c3841e056aac48a1519605ca78eba45
train_000.jsonl
1366385400
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. She may choose not to use all of the colors.However, there are some restrictions. For every two adjacent squares (squares that shares an edge) x and y, there is a color constraint in one of the forms: color(x) = color(y), or color(x) ≠ color(y). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class D { static boolean[] parse() { char[] c = next().toCharArray(); boolean[] ret = new boolean[c.length]; for (int i = 0; i < ret.length; i++) { ret[i] = c[i] == 'E'; } return ret; } static int countBad(int h, int w, boolean[][] b, boolean[][] inRow, boolean[][] inColumn) { int ret = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w - 1; j++) { if (inRow[i][j] != (b[i][j] == b[i][j + 1])) ret++; } } for (int i = 0; i < h - 1; i++) { for (int j = 0; j < w; j++) { if (inColumn[i][j] != (b[i][j] == b[i + 1][j])) ret++; } } return ret; } static void print(boolean[][] b) { writer.println("YES"); for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i].length; j++) { writer.print((b[i][j] ? "2" : "1") + " "); } writer.println(); } } static void solve() { int h = nextInt(), w = nextInt(), k = nextInt(); boolean[][] inRow = new boolean[h][]; boolean[][] inColumn = new boolean[h - 1][]; inRow[0] = parse(); for (int i = 0; i < h - 1; i++) { inColumn[i] = parse(); inRow[i + 1] = parse(); } int equations = h * (w - 1) + (h - 1) * w; int needGood = (3 * equations + 3) / 4, maxBad = equations - needGood; boolean[][] ans = new boolean[h][w]; if (countBad(h, w, ans, inRow, inColumn) <= maxBad) { print(ans); return; } if (k == 1) { writer.println("NO"); return; } if (w >= h) { for (int i = 0; i < h; i++) { for (int j = 0; j < w - 1; j++) { ans[i][j + 1] = ans[i][j] ^ (!inRow[i][j]); } } for (int i = 0; i < h - 1; i++) { int bad = 0; for (int j = 0; j < w; j++) { if (inColumn[i][j] != (ans[i][j] == ans[i + 1][j])) bad++; } if (2 * bad > w) { for (int j = 0; j < w; j++) { ans[i + 1][j] ^= true; } } } } else { for (int i = 0; i < h - 1; i++) { for (int j = 0; j < w; j++) { ans[i + 1][j] = ans[i][j] ^ (!inColumn[i][j]); } } for (int i = 0; i < w - 1; i++) { int bad = 0; for (int j = 0; j < h; j++) { if (inRow[j][i] != (ans[j][i] == ans[j][i + 1])) bad++; } if (2 * bad > h) { for (int j = 0; j < h; j++) { ans[j][i + 1] ^= true; } } } } print(ans); } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["3 4 4\nENE\nNNEE\nNEE\nENEN\nENN"]
1 second
["YES\n1 1 2 2\n3 4 1 1\n3 3 2 4"]
null
Java 7
standard input
[ "constructive algorithms" ]
a5f650b6f5737f654eb30f1e57ce03d6
The first line contains three integers h, w, k (2 ≀ h, w ≀ 1000, 1 ≀ k ≀ wΒ·h). The next 2h - 1 lines describe the color constraints from top to bottom, left to right. They contain w - 1, w, w - 1, w, ..., w - 1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means " = " and "N" means " ≠ ". The color constraints listed in the order they are depicted on the picture.
2,500
If there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next h lines, print w integers describing the coloring. Otherwise, print "NO" (without quotes).
standard output
PASSED
45272f96f993289982114d6bfed69650
train_000.jsonl
1366385400
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. She may choose not to use all of the colors.However, there are some restrictions. For every two adjacent squares (squares that shares an edge) x and y, there is a color constraint in one of the forms: color(x) = color(y), or color(x) ≠ color(y). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static boolean[][]H,V,M; static void output(PrintWriter out,int n,int m){ int x=-1,y; for(out.println("YES");n>++x;out.println()) for(y=0;m>y;out.print((M[x][y++]?2:1)+" ")); } static boolean oneColorFill(int n,int m){ int s=0,x=0,y; for(;n>x;++x) for(y=0;m>y;++y) s+=(n-1>x&&V[x][y]?1:0)+(m-1>y&&H[x][y]?1:0); return n*(m-1)+(n-1)*m>=s<<2; } static void HFirstFill(int n,int m){ int s,x=0,y=m-1; for(;0<y--;M[0][y]=H[0][y]^M[0][1+y]); while(n>++x){ for(y=m-1,s=M[x-1][y]^V[x-1][y]^M[x][y]?2:0;0<y--;s+=M[x-1][y]^V[x-1][y]^(M[x][y]=H[x][y]^M[x][1+y])?2:0); if(m<s) for(;m>++y;M[x][y]=!M[x][y]); } } static void VFirstFill(int n,int m){ int s,x=n-1,y=0; for(;0<x--;M[x][0]=V[x][0]^M[1+x][0]); while(m>++y){ for(x=n-1,s=M[x][y-1]^H[x][y-1]^M[x][y]?2:0;0<x--;s+=M[x][y-1]^H[x][y-1]^(M[x][y]=V[x][y]^M[1+x][y])?2:0); if(n<s) for(;n>++x;M[x][y]=!M[x][y]); } } public static void main(String[]args){ String z; ScanReader in=new ScanReader(System.in); int n=in.nextInt(),m=in.nextInt(),q=in.nextInt(),i=0,j; H=new boolean[n][m-1];V=new boolean[n-1][m]; for(M=new boolean[n][m];n-1>i;++i){ for(z=in.next(),j=-1;m-1>++j;H[i][j]='E'!=z.codePointAt(j)); for(z=in.next(),j=-1;m>++j;V[i][j]='E'!=z.codePointAt(j)); } for(z=in.next(),j=-1;m-1>++j;H[i][j]='E'!=z.codePointAt(j)); PrintWriter out=new PrintWriter(System.out); if(2>q) if(oneColorFill(n,m)) output(out,n,m);else out.print("NO"); else{if(n<m) HFirstFill(n,m);else VFirstFill(n,m);output(out,n,m);} out.close(); } } class ScanReader{ private final StreamTokenizer st; public ScanReader(Reader in){ if(null==in) throw new NullPointerException(); st=new StreamTokenizer(new BufferedReader(in)); } public ScanReader(InputStream in){ this(null!=in?new InputStreamReader(in):null); } public boolean hasNext(){ int ttype=0; try{ttype=st.nextToken();} catch(IOException e){throw new RuntimeException(e);} return StreamTokenizer.TT_EOF!=ttype; } public String next(){ if(!hasNext()) throw new NoSuchElementException(); return st.sval; } public int nextInt(){ if(!hasNext()) throw new NoSuchElementException(); return (int)st.nval; } }
Java
["3 4 4\nENE\nNNEE\nNEE\nENEN\nENN"]
1 second
["YES\n1 1 2 2\n3 4 1 1\n3 3 2 4"]
null
Java 7
standard input
[ "constructive algorithms" ]
a5f650b6f5737f654eb30f1e57ce03d6
The first line contains three integers h, w, k (2 ≀ h, w ≀ 1000, 1 ≀ k ≀ wΒ·h). The next 2h - 1 lines describe the color constraints from top to bottom, left to right. They contain w - 1, w, w - 1, w, ..., w - 1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means " = " and "N" means " ≠ ". The color constraints listed in the order they are depicted on the picture.
2,500
If there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next h lines, print w integers describing the coloring. Otherwise, print "NO" (without quotes).
standard output
PASSED
3bf5fc54c0ea4bb4a2c1a1c599fc3ef9
train_000.jsonl
1366385400
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. She may choose not to use all of the colors.However, there are some restrictions. For every two adjacent squares (squares that shares an edge) x and y, there is a color constraint in one of the forms: color(x) = color(y), or color(x) ≠ color(y). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int height = in.readInt(); int width = in.readInt(); int colorCount = in.readInt(); boolean[][] inRows = new boolean[height][width - 1]; boolean[][] inColumns = new boolean[width][height - 1]; for (int i = 0; i < height; i++) { for (int j = 0; j < width - 1; j++) inRows[i][j] = in.readCharacter() == 'E'; if (i != height - 1) { for (int j = 0; j < width; j++) inColumns[j][i] = in.readCharacter() == 'E'; } } if (colorCount == 1) { int total = width * (height - 1) + height * (width - 1); total -= total / 4; for (boolean[] row : inRows) { for (boolean b : row) { if (b) total--; } } for (boolean[] row : inColumns) { for (boolean b : row) { if (b) total--; } } if (total > 0) out.printLine("NO"); else { out.printLine("YES"); int[] row = new int[width]; Arrays.fill(row, 1); for (int i = 0; i < height; i++) out.printLine(row); } return; } out.printLine("YES"); boolean shouldRotate = false; if (height > width) { int temp = height; height = width; width = temp; shouldRotate = true; boolean[][] temp2 = inRows; inRows = inColumns; inColumns = temp2; } int[][] answer = new int[height][width]; answer[0][0] = 1; for (int i = 1; i < width; i++) { if (inRows[0][i - 1]) answer[0][i] = answer[0][i - 1]; else answer[0][i] = 3 - answer[0][i - 1]; } for (int i = 1; i < height; i++) { int current = 0; answer[i][0] = 1; if ((answer[i][0] == answer[i - 1][0]) != inColumns[0][i - 1]) current++; for (int j = 1; j < width; j++) { if (inRows[i][j - 1]) answer[i][j] = answer[i][j - 1]; else answer[i][j] = 3 - answer[i][j - 1]; if ((answer[i][j] == answer[i - 1][j]) != inColumns[j][i - 1]) current++; } if (current > width - current) { for (int j = 0; j < width; j++) answer[i][j] = 3 - answer[i][j]; } } if (shouldRotate) { int[][] temp = new int[width][height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) temp[j][i] = answer[i][j]; } answer = temp; } for (int[] row : answer) out.printLine(row); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3 4 4\nENE\nNNEE\nNEE\nENEN\nENN"]
1 second
["YES\n1 1 2 2\n3 4 1 1\n3 3 2 4"]
null
Java 7
standard input
[ "constructive algorithms" ]
a5f650b6f5737f654eb30f1e57ce03d6
The first line contains three integers h, w, k (2 ≀ h, w ≀ 1000, 1 ≀ k ≀ wΒ·h). The next 2h - 1 lines describe the color constraints from top to bottom, left to right. They contain w - 1, w, w - 1, w, ..., w - 1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means " = " and "N" means " ≠ ". The color constraints listed in the order they are depicted on the picture.
2,500
If there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next h lines, print w integers describing the coloring. Otherwise, print "NO" (without quotes).
standard output
PASSED
845a5aa514fd6d1d7d31754342a1236f
train_000.jsonl
1366385400
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. She may choose not to use all of the colors.However, there are some restrictions. For every two adjacent squares (squares that shares an edge) x and y, there is a color constraint in one of the forms: color(x) = color(y), or color(x) ≠ color(y). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class D { private void solve() throws IOException { int h = nextInt(); int w = nextInt(); int k = nextInt(); char[][] e1 = new char[h][]; char[][] e2 = new char[h - 1][]; for (int i = 0; i < h - 1; i++) { e1[i] = nextToken().toCharArray(); e2[i] = nextToken().toCharArray(); } e1[h - 1] = nextToken().toCharArray(); int all = (h - 1) * w + h * (w - 1); if (k == 1) { int ne = 0; for (char[] s: e1) { for (char c: s) { if (c == 'N') { ne++; } } } for (char[] s: e2) { for (char c: s) { if (c == 'N') { ne++; } } } if (ne * 4 > all) { println("NO"); } else { println("YES"); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { print("1 "); } println(""); } } return; } if (h * (w - 1) < w * (h - 1)) { char[][] e3 = new char[w][h - 1]; char[][] e4 = new char[w - 1][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h - 1; j++) { e3[i][j] = e2[j][i]; } } for (int i = 0; i < w - 1; i++) { for (int j = 0; j < h; j++) { e4[i][j] = e1[j][i]; } } int[][] ans = fill(w, h, e3, e4); println("YES"); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { print((1 + ans[j][i]) + " "); } println(""); } return; } int[][] ans = fill(h, w, e1, e2); println("YES"); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { print((1 + ans[i][j]) + " "); } println(""); } } private int[][] fill(int h, int w, char[][] e1, char[][] e2) { int[][] ans = new int[h][w]; fill(ans[0], e1[0]); for (int i = 1; i < h; i++) { fill(ans[i], e1[i]); int s = 0; for (int j = 0; j < w; j++) { if (!(e2[i - 1][j] == 'E' && ans[i - 1][j] == ans[i][j] || e2[i - 1][j] == 'N' && ans[i - 1][j] != ans[i][j])) { s++; } } if (s * 2 > w) { for (int j = 0; j < w; j++) { ans[i][j] = (ans[i][j] + 1) & 1; } } } return ans; } private void fill(int[] a, char[] e) { for (int i = 1; i < a.length; i++) { if (e[i - 1] == 'E') { a[i] = a[i - 1]; } else { a[i] = (a[i - 1] + 1) & 1; } } } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new D().run(); System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }
Java
["3 4 4\nENE\nNNEE\nNEE\nENEN\nENN"]
1 second
["YES\n1 1 2 2\n3 4 1 1\n3 3 2 4"]
null
Java 7
standard input
[ "constructive algorithms" ]
a5f650b6f5737f654eb30f1e57ce03d6
The first line contains three integers h, w, k (2 ≀ h, w ≀ 1000, 1 ≀ k ≀ wΒ·h). The next 2h - 1 lines describe the color constraints from top to bottom, left to right. They contain w - 1, w, w - 1, w, ..., w - 1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means " = " and "N" means " ≠ ". The color constraints listed in the order they are depicted on the picture.
2,500
If there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next h lines, print w integers describing the coloring. Otherwise, print "NO" (without quotes).
standard output
PASSED
4cacc0d6cb94b8fd9821c08556c1642e
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemBPassword solver = new ProblemBPassword(); solver.solve(1, in, out); out.close(); } static class ProblemBPassword { String q; int N; int[] zv; TreeSet<Integer> ts = new TreeSet<Integer>(); int[] f = new int[1_000_001]; void add(int i) { f[i]++; ts.add(i); } void rem(int i) { f[i]--; if (f[i] == 0) ts.remove(i); } public void solve(int testNumber, FastScanner s, PrintWriter out) { q = s.next(); zv = Z.values(q); N = zv.length; if (N < 3) { out.println("Just a legend"); return; } for (int i = 1; i < N; i++) add(zv[i]); int b = N - 1; while (b > 0) { // check suffix int fx = (N - 1) - (b - 1); if (zv[fx] == b) { // check interior rem(zv[fx]); if (ts.last() >= b) { out.println(q.substring(0, b)); return; } add(zv[fx]); } b--; } out.println("Just a legend"); } } static class Z { public static int[] values(String string) { int n = string.length(); char[] s = string.toCharArray(); int[] z = new int[n]; z[0] = n; int L = 0, R = 0; int[] left = new int[n], right = new int[n]; for (int i = 1; i < n; ++i) { if (i > R) { L = R = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } left[i] = L; right[i] = R; } return z; } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
ab9fcecc9e4d157a630e668ec86acab5
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; public class Main { private static final String LEGEND = "Just a legend"; public static void main(String[] args) throws IOException { byte[] input = new byte[1000002]; int size = System.in.read(input) - 2; getResult(input, size); } private static void getResult(byte[] arr, int size) { int[] zbuff = zFunc(arr, size); for (int i = 1; i < zbuff.length; i++) { if (zbuff[i] == zbuff.length - i && has(zbuff, zbuff[i], i)) { System.out.write(arr, 0, zbuff[i]); System.out.println(); return; } } System.out.println(LEGEND); } public static boolean has(int[] zbuff, int curr, int index) { for (int i = 1; i < index; i++) { if (zbuff[i] >= curr) { return true; } } return false; } public static int[] zFunc(byte[] arr, int size) { int[] result = new int[size]; for (int i = 1, left = 0, right = 0; i < size; i++) { if (i <= right) { result[i] = Math.min(right - i + 1, result[i - left]); } while (i + result[i] < size && arr[i + result[i]] == arr[result[i]]) { result[i]++; } if (i + result[i] - 1 > right) { left = i; right = i + result[i] - 1; } } return result; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
3bbc717b0b1ba1642509ced93251a862
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; import java.io.*; public class _0126_B_Password { public static void main(String[] args) throws IOException { String s = read(); int N = s.length(); int lps[] = new int[N]; for(int i = 1, j = 0; i<N; ) { if(s.charAt(i) == s.charAt(j)) { lps[i++] = ++j; } else if(j != 0) { j = lps[j-1]; } else { i++; } } for(int i = 1, j = 0; i<N-1; ) { if(s.charAt(i) == s.charAt(j)) { i++; j++; if(j == lps[N-1]) { println(s.substring(0, lps[N-1])); exit(); } } else if(j != 0) { j = lps[j-1]; } else i++; } if(lps[N-1] != 0 && lps[lps[N-1]-1] != 0) { println(s.substring(0, lps[lps[N-1]-1])); exit(); } println("Just a legend"); exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1000001]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static long readLong() throws IOException { long ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static double readDouble() throws IOException { double ret = 0, div = 1; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (c == '.') { while ((c = Read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
904be94c7923285d77d2e3a46456a341
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; public class cf126_B_Password { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer st; public static PrintWriter pr = new PrintWriter(System.out); public static String getString() { try { return br.readLine(); }catch (Exception e) { e.printStackTrace(); System.exit(-1); return ""; } } public static Integer getNextInteger() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(getString()); } return Integer.parseInt(st.nextToken()); } static long fme(long v, long pow) { if (pow == 0) return 1l; if (pow == 1) return v; long ret = fme(v, pow/2); ret *= ret; if (pow % 2 == 1) { ret *= v; } return ret; } public static void main(String[] args) { String input = getString(); long dpn = 0, blk = 0; long pengali = 1; // HashSet<Long> matches = new HashSet<>(); TreeSet<Integer> matchesLength = new TreeSet<>(); for(int i =0; i < input.length() - 1;i++) { dpn *= 27; dpn += input.charAt(i) - 'a' + 1; int charBaru = input.charAt(input.length() - 1 - i) - 'a' + 1; blk = (charBaru) * pengali + blk; pengali *= 27; if (dpn == blk) { // matches.add(dpn); matchesLength.add(i+1); } // System.out.println(dpn+" "+blk); } long hashes[] = new long[input.length()]; long hashKeyPow[] = new long[input.length()]; for(int i =0 ;i < input.length();i++) { hashes[i] = i > 0 ? hashes[i-1] : 0; hashes[i] *= 27; hashes[i] += input.charAt(i) - 'a' + 1; hashKeyPow[i] = i > 0 ? hashKeyPow[i-1] * 27 : 1; } int output = 0; // System.out.println(matchesLength); for(int i = 1 ;i < input.length() - 1;i++) { int l = 0, r = input.length() - i - 2; // System.out.println(i+" : "+ input.charAt(i)); while(l<=r) { int mid = (l+r) / 2; // if(mid+i >= input.length()-1) { // r = mid - 1; // continue; // } long hashPrefix = hashes[mid]; long hashSub = hashes[mid+i] - (hashes[i-1] * hashKeyPow[mid+1]); // System.out.println(mid +" "+l +"," + r+ " "+hashPrefix + " "+hashSub); if (hashPrefix == hashSub) { l = mid + 1; } else { r = mid - 1; } } int longestMatchSubstr = r + 1; if (longestMatchSubstr > 0) { // System.out.println("longest match"+longestMatchSubstr); Integer pjg = matchesLength.lower(longestMatchSubstr+1); if (pjg != null) { output = Math.max(output, pjg); } } } if (output > 0) { pr.println(input.substring(0, output)); } else { pr.println("Just a legend"); } pr.flush(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
7bc60a5dc822db0c421a09e28e59e479
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; public class cf126_B_Password { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer st; public static PrintWriter pr = new PrintWriter(System.out); public static String getString() { try { return br.readLine(); }catch (Exception e) { e.printStackTrace(); System.exit(-1); return ""; } } public static Integer getNextInteger() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(getString()); } return Integer.parseInt(st.nextToken()); } static long fme(long v, long pow) { if (pow == 0) return 1l; if (pow == 1) return v; long ret = fme(v, pow/2); ret *= ret; if (pow % 2 == 1) { ret *= v; } return ret; } public static void main(String[] args) { String input = getString(); long dpn = 0, blk = 0; long pengali = 1; // HashSet<Long> matches = new HashSet<>(); TreeSet<Integer> matchesLength = new TreeSet<>(); for(int i =0; i < input.length() - 1;i++) { dpn *= 27; dpn += input.charAt(i) - 'a' + 1; int charBaru = input.charAt(input.length() - 1 - i) - 'a' + 1; blk = (charBaru) * pengali + blk; pengali *= 27; if (dpn == blk) { // matches.add(dpn); matchesLength.add(i+1); } // System.out.println(dpn+" "+blk); } long hashes[] = new long[input.length()]; long hashKeyPow[] = new long[input.length()]; for(int i =0 ;i < input.length();i++) { hashes[i] = i > 0 ? hashes[i-1] : 0; hashes[i] *= 27; hashes[i] += input.charAt(i) - 'a' + 1; hashKeyPow[i] = i > 0 ? hashKeyPow[i-1] * 27 : 1; } int output = 0; // System.out.println(matchesLength); for(int i = 1 ;i < input.length() - 1;i++) { int l = 0, r = input.length() - 2; // System.out.println(i+" : "+ input.charAt(i)); while(l<=r) { int mid = (l+r) / 2; if(mid+i >= input.length()-1) { r = mid - 1; continue; } long hashPrefix = hashes[mid]; long hashSub = hashes[mid+i] - (hashes[i-1] * hashKeyPow[mid+1]); // System.out.println(mid +" "+l +"," + r+ " "+hashPrefix + " "+hashSub); if (hashPrefix == hashSub) { l = mid + 1; } else { r = mid - 1; } } int longestMatchSubstr = r + 1; if (longestMatchSubstr > 0) { // System.out.println("longest match"+longestMatchSubstr); Integer pjg = matchesLength.lower(longestMatchSubstr+1); if (pjg != null) { output = Math.max(output, pjg); } } } if (output > 0) { pr.println(input.substring(0, output)); } else { pr.println("Just a legend"); } pr.flush(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
5783a917b6bb6be6dd2ef21369d5457f
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
/* *created by Kraken on 25-04-2020 at 11:56 */ //package com.kraken.cf.practice; import java.util.*; import java.io.*; public class B126 { public static void main(String[] args) { FastReader sc = new FastReader(); String s = sc.next(); int n = s.length(); if (n > 2) { int[] pre = new int[n]; for (int i = 1; i < n; i++) { int j = pre[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) j = pre[j - 1]; if (s.charAt(i) == s.charAt(j)) j++; pre[i] = j; } // System.out.println(Arrays.toString(pre)); if (pre[n - 1] == 0) { System.out.println("Just a legend"); return; } for (int i = 0; i < n - 1; i++) if (pre[i] == pre[n - 1]) { System.out.println(s.substring(0, pre[n - 1])); return; } int j = pre[pre[n - 1] - 1]; if (j > 0) { System.out.println(s.substring(0, j)); return; } } System.out.println("Just a legend"); } 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
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
8af74a785f3f46b4b947701aa1e22f13
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = sc.nextLine(); int z[] = zAlg(s.toCharArray()); //System.out.println(Arrays.toString(z)); int n = z.length; int maxSuf = 0; for(int i = 0; i < n; ++i) if(z[i] == n - i) maxSuf = Math.max(maxSuf, z[i]); if(maxSuf == 0) { System.out.println("Just a legend"); return; } for(int i = 0; i < n; ++i) if(z[i] >= maxSuf && z[i] != n - i) { System.out.println(s.substring(0, maxSuf)); return; } for(int i = 1; i < maxSuf; ++i) { if(z[i] >= maxSuf - i) { System.out.println(s.substring(0, maxSuf - i)); return; } } out.println("Just a legend"); out.flush(); out.close(); } private static int[] zAlg(char[] s) { int n = s.length; int z[] = new int[n]; for(int i = 1, L = 0, R = 0; i < n; ++i) { if(R < i) { L = R = i; while(R < n && s[R] == s[R - L]) R++; z[i] = R - L; R--; } else { int k = i - L; if(i + z[k] <= R) z[i] = z[k]; else { L = i; while(R < n && s[R] == s[R - L]) R++; z[i] = R - L; R--; } } } return z; } static class Pair implements Comparable<Pair>{ long a; int b; public Pair(long x, int y) { a = x; b = y; } @Override public int compareTo(Pair p) { if(Long.compare(a, p.a) == 0) return Integer.compare(b, p.b); return Long.compare(a, p.a); } } static class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
1ee613986b403dfd688c4dce92c6eee1
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char s[] = sc.nextLine().toCharArray(); int n = s.length; int kmp[] = new int[n]; kmp[0] = 0; int i = 1, j = 0; int max = 0; while(i < n) { while(j > 0 && s[i] != s[j]) j = kmp[j - 1]; if(s[i] == s[j]) kmp[i++] = ++j; else kmp[i++] = 0; if(i < n) max = Math.max(max, kmp[i - 1]); } if(kmp[n - 1] > 0 && max >= kmp[n - 1]) { out.println(new String(s).substring(0, kmp[n - 1])); } else { max = kmp[n - 1]; if(max != 0) max = kmp[max - 1]; if(max == 0) out.println("Just a legend"); else out.println(new String(s).substring(0, max)); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int a, b, d; public Pair(int x, int y) { a = x; b = y; d = Math.abs(x) + Math.abs(y); } @Override public int compareTo(Pair p) { return d - p.d; } @Override public String toString() { return a + " " + b; } } static class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
78e981d8a77d72dc57f171bdfbac1caf
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
/* D A R K L _ _ O R D D A K / | | \ L O R D A R _ / | | \ _ K L O R D A R K _ / | _ | \ _ L O R D D R K L _ / _ | _ | \\ | _ \ O R D D R K _ / _ | _ | \ \ | _ \ L O R D A R _ / _ / | / / \ \ | \ _ \ _ K L O D D _ / _ / | / / \ \ | \ _ \ _ A K _ / _ / | / / _ \ \ | \ _ \ _ L O R D A _ / _ / | / / _ \ \ | \ _ \ _ R K _ / _ / | | | | \ (O) / | | \ _ \ _ O D _ / _ / | | | | \ / | | \ _ \ _ D A / _ / | | | \ | \ _ \|/ / | | | \ _ \ K / _ / | | | \ | \ _ V / | | | \ _ \ L / / | | | \ _ / \ _ _ / | | | \ \ / / | | | | | | | \ \ / / | | | \ \ ROWECHEN / / | | | \ \ / / _ _ | | | \ \ ZHONG / / | | | _ _ \ \ / / _ / \ | | | | \ / \ \ / / \ / | | | | / \ _ \ \ / / _ / \ | | | | \ \ / / | | | | / \ _ \ \ / / / \ \ \ \ / / \ \ / / / / \ \ \ \ / / \ \ \ \ / / \ \ / / / / \ \ / \|/ \|/ | | | \|/ \|/ L O \|/ | | | | \|/ R D A R K L / _ | | | _ \ O R D D A R L O R / _ | | | _ \ D D A R L O R D / / / _ | _ | | \ _ \ D A R K O R D / / / _ | | _ | | \ _ \ D A R K L R D D A R | / / | | / | | \ / | | \ | K L O R D A R K | / / | | / | | \ / | | \ | L O R D A R / \ / | | | / | | / \ / K L O R D D A / \ / | | | / | | / \/ R K L O R D D / | / \ | \ / A R K L O R D A R K L / | / \ | \/ O R D D R K L O R D \ / | D A R K L O R D A R \/ | K L O R D D */ //TEMPLATE V2 import java.io.*; import java.util.*; public class Main { //Solution goes below: ------------------------------------ private static void getZarr(char[] str, int[] Z) { int L = 0, R = 0; for(int i = 1; i < len; ++i) { if(i > R){ L = R = i; while(R < len && str[R - L] == str[R]) R++; Z[i] = R - L; R--; }else{ int k = i - L; if(Z[k] < R - i + 1) Z[i] = Z[k]; else{ L = i; while(R < len && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } } } public static int[] Z; public static int len; public static void solution() throws IOException{ char[] s = nextLine().toCharArray(); len = s.length; Z = new int[len]; getZarr(s, Z); /*for(int i:Z){ print(i); } println();*/ int res = 0; int[] subsize = new int[len]; for(int i:Z){ subsize[i]++; } for(int i=len-2;i>=0;i--){ subsize[i]+=subsize[i+1]; } for(int i = len-1;i>=1;i--) { if (subsize[i] >= 2) { if (Z[len - i] == i) { res = i; break; } } } if(res==0){ println("Just a legend"); }else{ for(int i=0;i<res;i++){ print(s[i]); } println(); } } //Solution goes above: ------------------------------------ public static final String IN_FILE = ""; public static final String OUT_FILE = ""; //-------------------- ------------------------------------ //IO public static BufferedReader br; public static StringTokenizer st; public static BufferedWriter bw; public static void main(String[] args) throws IOException{ if(IN_FILE==""){ br = new BufferedReader(new InputStreamReader(System.in)); }else{ try { br = new BufferedReader(new FileReader(IN_FILE)); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } if (OUT_FILE==""){ bw = new BufferedWriter(new OutputStreamWriter(System.out)); }else{ try { bw = new BufferedWriter (new FileWriter(OUT_FILE) ); } catch (FileNotFoundException e) { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } } solution(); bw.close();//Flushes too. } public static String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public static String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } public static void println(Object s) throws IOException{ bw.write(s.toString()+"\n"); } public static void println() throws IOException{ bw.newLine(); } public static void print(Object s) throws IOException{ bw.write(s.toString()); } public static void flush() throws IOException{//Useful for debug bw.flush(); } //Other public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
2bbfd77a9ee2c95390230e104f02d36b
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; public class KMP { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int ans = kmp(s,s); if (ans == -1 || s.length() < 3) { System.out.println("Just a legend"); } else { System.out.println(s.substring(0, ans)); } sc.close(); } public static int kmp(String s, String w) { int[] btarr = new int[w.length()]; int i = 1; int j = 0; btarr[0] = 0; while (i < btarr.length) { if (w.charAt(i) != w.charAt(j)) { if (j > 0) { j = btarr[j-1]; } else { btarr[i] = 0; ++i; } } else { btarr[i] = j + 1; ++i; ++j; } } int btSuffix = btarr[w.length()-1]; // System.out.println(Arrays.toString(btarr)); // System.out.println(btSuffix); if (btSuffix == 0) { return -1; } else { for (int k = 1; k < btarr.length - 1; k++) { if (btarr[k] == btSuffix) { return btSuffix; } } //System.out.println(btarr[btSuffix]); if (btarr[btSuffix-1] != 0) { return btarr[btSuffix-1]; } } return -1; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
9c26d6df8270fd7159b84d6f7d92d7cf
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class l050 { public static void main(String[] args) throws Exception { // StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next()); StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); String s = stok.nextToken(); int[] Z = Z(s); int len = Z.length; ArrayList<Integer> list = new ArrayList<Integer>(); int max = Integer.MIN_VALUE; for(int i=len-1;i>0;i--) { if(i+Z[i]==len) { list.add(Z[i]); max = Math.max(max, Z[i]-1); } else max = Math.max(max, Z[i]); } Collections.sort(list,(x,y)->Integer.compare(y, x)); int ptr=0; int res =-1; while(ptr<list.size()) { int v = list.get(ptr); if(v<=max) { res=v; break; } ptr++; } if(res<=0) System.out.println("Just a legend"); else System.out.println(s.substring(0, res)); } private static int[] Z(String s) { char[] str = s.toCharArray(); int n = str.length; int L, R, k; int[] Z = new int[n]; L = R = 0; for (int i = 1; i < n; ++i) { if (i > R) { L = R = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { k = i-L; if (Z[k] < R-i+1) Z[i] = Z[k]; else { L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } } return Z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
937a474e47246b6ba6342e07f843a663
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.StringTokenizer; public class p009 { public static void main(String args[]) throws Exception { StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); char[] s = stok.nextToken().toCharArray(); int[] z = Z(s); int maxe=0,maxm=0,n=s.length; int[] a = new int[n+1],b=new int[n+1]; for(int i=n-1;i>0;i--) { if(z[i]+i>=n) { if(z[i]-1>0) a[z[i]-1]=1;; b[z[i]]=2; } else if(z[i]>0) a[z[i]]=1; } int x=Integer.MIN_VALUE,y=Integer.MIN_VALUE; for(int i=n;i>0 && (x==Integer.MIN_VALUE||y==Integer.MIN_VALUE);i--) { if(a[i]==1) x=Math.max(x,i); if(x!=Integer.MIN_VALUE)if(b[i]==2) y=Math.max(y, i); } int v = Math.min(x, y); if(v==Integer.MIN_VALUE) sb.append("Just a legend"); else for(int i=0;i<v;i++) sb.append(s[i]); System.out.println(sb); } private static int[] Z(char[] str) { int n = str.length; int L, R, k; int[] Z = new int[n]; L = R = 0; for (int i = 1; i < n; ++i) { if (i > R) { L = R = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { k = i-L; if (Z[k] < R-i+1) Z[i] = Z[k]; else { L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } } return Z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
03384e34011b3af924fdfe04779bd2f8
train_000.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import sun.reflect.generics.tree.Tree; import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { solver s = new solver(); long t = 1; while (t > 0) { s.solve(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); token = null; } public String sn() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int ni() { return Integer.parseInt(sn()); } public String snl() throws IOException { return br.readLine(); } public long nlo() { return Long.parseLong(sn()); } public double nd() { return Double.parseDouble(sn()); } public int[] na(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.ni(); return a; } public long[] nal(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nlo(); return a; } } static class ascend implements Comparator<pair> { public int compare(pair o1, pair o2) { return o2.b - o1.b; } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; static void shuffle(int a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; int x = a[t]; a[t] = a[i]; a[i] = x; } } static void shufflel(long a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; long x = a[t]; a[t] = a[i]; a[i] = x; } } static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } static boolean valid(int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) { // System.out.println(i+" /// "+j); return true; } else { // System.out.println(i+" //f "+j); return false; } } static void seive() { for (int i = 2; i < 101; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 101; j += i) v[j] = true; } } } static int binary(LinkedList<Integer> a, long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a.get(mid) == val) { r = mid - 1; ans = mid; } else if (a.get(mid) > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } /* void dijsktra(int s, List<pair> l[], int n) { PriorityQueue<pair> pq = new PriorityQueue<>(new ascend()); int dist[] = new int[100005]; boolean v[] = new boolean[100005]; for (int i = 1; i <= n; i++) dist[i] = 1000000000; dist[s] = 0; for (int i = 1; i < n; i++) { if (i == s) pq.add(new pair(s, 0)); else pq.add(new pair(i, 1000000000)); } while (!pq.isEmpty()) { pair node = pq.remove(); v[node.a] = true; for (int i = 0; i < l[node.a].size(); i++) { int v1 = l[node.a].get(i).a; int w = l[node.a].get(i).b; if (v[v1]) continue; if ((dist[node.a] + w) < dist[v1]) { dist[v1] = dist[node.a] + w; pq.add(new pair(v1, dist[v1])); } } } }*/ } static class pair { int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static int inf = 5000013; static class solver { DecimalFormat df = new DecimalFormat("0.00"); extra e = new extra(); int mod = 1000000007; boolean v[] = new boolean[1001]; char t[]; void solve() throws IOException { String s = sc.sn(); int n = s.length(); String ans = "Just a legend"; zAlgo(s, n); // System.out.println(Arrays.toString(z)); int m = 0, x = 0; for (int i = 0; i < n; i++) { if (z[i] + i == n && m >= z[i]) x = Math.max(z[i], x); m = Math.max(m, z[i]); } if (x == 0) out.println("Just a legend"); else { for (int i = 0; i < x; i++) out.print(s.charAt(i)); out.println(); } } int z[]; void zAlgo(String s, int n) { z = new int[n]; int right = 0, left = 0; char c[] = s.toCharArray(); for (int i = 1; i < n; i++) { if (i > right) { left = i; right = i; while (right < n && c[right] == c[right - left]) { right++; } z[i] = right - left; right--; } else { int ii = i - left; if (z[ii] < right - i + 1) { z[i] = z[ii]; } else { left = i; while (right < n && c[right] == c[right - left]) { right++; } z[i] = right - left; right--; } } } } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 8
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
a7d7e0175741f784bf75577ec90af753
train_000.jsonl
1591281300
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$.
256 megabytes
//package round647; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } void go() { int n = ni(), P = ni(); int mod = 1000000007; int[] a = na(n); if(P == 1){ out.println(n % 2 == 0 ? 0 : 1); return; } a = shuffle(a, gen); Arrays.sort(a); long bal = 0; long ans = 0; for(int i = n-1;i >= 0;i--){ if(i < n-1){ if(bal != 0){ int e = a[i+1] - a[i]; for(int j = 0;j < e;j++){ if(Math.abs(bal) >= 1L<<24)break; bal *= P; } } } if(bal <= 0){ bal++; ans += pow(P, a[i], mod); }else{ bal--; ans -= pow(P, a[i], mod); } } if(bal < 0){ bal = -bal; } ans %= mod; if(ans < 0)ans += mod; out.println(ans); } public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } Random gen = new Random(); public static int[] shuffle(int[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } 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 B().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89"]
2 seconds
["4\n1\n146981438\n747093407"]
NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$.
Java 11
standard input
[ "implementation", "sortings", "greedy", "math" ]
ff4fce15470e5dbd1153bd23b26896f1
Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$Β β€” the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$.
1,900
Output one integerΒ β€” the reminder of division the answer by $$$1\,000\,000\,007$$$.
standard output
PASSED
5c5dfe06a416b035d5e72dde00585140
train_000.jsonl
1591281300
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.HashSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); EJohnnyAndGrandmaster solver = new EJohnnyAndGrandmaster(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class EJohnnyAndGrandmaster { int mod = 1000000007; int[] counter = new int[1000010]; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), p = in.nextInt(); int[] k = in.readIntArray(n); if (p == 1) { out.println(n % 2); return; } AUtils.sort(k); AUtils.reverse(k); int big = -1; long ans = 0; HashSet<Integer> seen = new HashSet<>(); for (int j : k) { if (big == -1) { ans = Utils.mod_exp(p, j, mod); big = j; } else { ans -= Utils.mod_exp(p, j, mod); if (ans < 0) ans += mod; int id = j; seen.add(j); while (id < big && ++counter[id] == p) { counter[id++] = 0; seen.add(id); } if (id == big) { big = -1; ans = 0; counter[id] = 0; } } } for (int x : seen) counter[x] = 0; out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public String next() { int c; while (isSpaceChar(c = this.read())) { ; } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(i); } } static class Utils { public static long mod_exp(long b, long e, long mod) { long res = 1; while (e > 0) { if ((e & 1) == 1) res = (res * b) % mod; b = (b * b) % mod; e >>= 1; } return res % mod; } } static class AUtils { public static void reverse(int[] arr) { for (int i = 0, j = arr.length - 1; i < j; i++, j--) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } public static void sort(int[] arr) { shuffle(arr); Arrays.sort(arr); } public static void shuffle(int[] arr) { for (int i = 1; i < arr.length; i++) { int j = (int) (Math.random() * (i + 1)); if (i != j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } } } }
Java
["4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89"]
2 seconds
["4\n1\n146981438\n747093407"]
NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$.
Java 11
standard input
[ "implementation", "sortings", "greedy", "math" ]
ff4fce15470e5dbd1153bd23b26896f1
Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$Β β€” the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$.
1,900
Output one integerΒ β€” the reminder of division the answer by $$$1\,000\,000\,007$$$.
standard output
PASSED
8dc2d7b391df9d4ea4b803ed7d20f533
train_000.jsonl
1591281300
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class TestClass { static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final int readInt() throws IOException { return (int) readLong(); } public final long readLong() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new IOException(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public final long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static long mulmod(long a, long b, long mod) { long res = 0; // Initialize result a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) { res = (res + a) % mod; } // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } static long pow(long a, long b, long MOD) { long x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y); if (x > MOD) x %= MOD; } y = (y * y); if (y > MOD) y %= MOD; b /= 2; } return x; } static long[] f = new long[100001]; static long InverseEuler(long n, long MOD) { return pow(n, MOD - 2, MOD); } static long C(int n, int r, long MOD) { return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD; } public static class SegmentTree { long[] tree; long[] lazy; int n; public SegmentTree(long[] arr) { n = arr.length; tree = new long[arr.length * 5]; lazy = new long[arr.length * 5]; build(arr, 0, arr.length - 1, 0); } private void build(long[] arr, int s, int e, int pos) { if (s == e) { tree[pos] = arr[s]; return; } int m = (s + e) / 2; build(arr, s, m, 2 * pos + 1); build(arr, m + 1, e, 2 * pos + 2); tree[pos] = Math.max(tree[2 * pos + 1], tree[2 * pos + 2]); } public void update(int s, int e, long val) { updateUtil(s, e, val, 0, n - 1, 0); } public long get(int s, int e) { return getUtil(s, e, 0, n - 1, 0); } private long getUtil(int gs, int ge, int s, int e, int pos) { if (s > e || s > ge || e < gs) return Long.MIN_VALUE; if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (s != e) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (s >= gs && e <= ge) { return tree[pos]; } int m = (s + e) / 2; return Math.max(getUtil(gs, ge, s, m, 2 * pos + 1), getUtil(gs, ge, m + 1, e, 2 * pos + 2)); } private void updateUtil(int us, int ue, long val, int s, int e, int pos) { if (s > e || s > ue || e < us) return; if (lazy[pos] != 0) { tree[pos] += lazy[pos]; if (s != e) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if (s >= us && e <= ue) { tree[pos] += val; if (s != e) { lazy[2 * pos + 1] += val; lazy[2 * pos + 2] += val; } return; } int m = (s + e) / 2; updateUtil(us, ue, val, s, m, 2 * pos + 1); updateUtil(us, ue, val, m + 1, e, 2 * pos + 2); tree[pos] = Math.max(tree[2 * pos + 1], tree[2 * pos + 2]); } } static int[] h = {0, 0, -1, 1}; static int[] v = {1, -1, 0, 0}; public static class Pair { public int x, y, p; public Pair(int d, int y) { this.x = d; this.y = y; } } static long compute_hash(String s) { int p = 31; int m = 1000000007; long hash_value = 0; long p_pow = 1; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } public static void main(String[] args) throws Exception { //https://i...content-available-to-author-only...e.com/ebRGa6 InputReader in = new InputReader(System.in); long t = in.readLong(); while (t-- > 0) { long n = in.readLong(); long p = in.readLong(); long[] nums = new long[(int) n]; for (int i = 0; i < n; ++i) { nums[i] = in.readLong(); } if (p == 1) { System.out.println((n%2 == 0) ? 0 : 1); continue; } Arrays.sort(nums); long finaA = 0; for (long i = n-1; i >= 0; ) { long lookF = nums[(int) i]; long countF = 1; long answer = pow(p, lookF, 1000000007); boolean found = false; for (--i; i >= 0 && countF > 0; --i) { long diff = lookF - nums[(int) i]; for (int k = 0; k < diff; ++k) { countF *= p; if (countF - 1 > i) { found = true; while (i >= 0) { answer = (answer - pow(p, nums[(int) i], 1000000007) + 1000000007) % 1000000007; i--; } } if (found) break; } if (found) break; countF -= 1; lookF = nums[(int) i]; answer = (answer - pow(p, nums[(int) i], 1000000007) + 1000000007) % 1000000007; } finaA = answer; if (found) break; } System.out.println(finaA%1000000007); } } private static long solve(long[][] dp, int n, int r) { if (n == 0) { if (r == 0) return 1; else return 0; } if (r <= 0) return 0; if (dp[n][r] != -1) return dp[n][r]; long answer = 0; for (int i = 1; i < n; ++i) { answer += solve(dp, n - 1, r - i); } dp[n][r] = answer; return answer; } static int gcd(int a, int b) { while (b != 0) { int t = a; a = b; b = t % b; } return a; } class Solution { public int maxProduct(int[] nums) { PriorityQueue<Integer> p = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer integer, Integer t1) { return Integer.compare(t1, integer); } }); for (int i = 0; i < nums.length; ++i) { p.add(nums[i]); } int f = p.remove(); int s = p.remove(); return (f - 1) * (s - 1); } } static boolean submit = true; static void debug(String s) { if (!submit) System.out.println(s); } static void debug(int s) { if (!submit) System.out.println(s); } }
Java
["4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89"]
2 seconds
["4\n1\n146981438\n747093407"]
NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$.
Java 11
standard input
[ "implementation", "sortings", "greedy", "math" ]
ff4fce15470e5dbd1153bd23b26896f1
Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$Β β€” the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$.
1,900
Output one integerΒ β€” the reminder of division the answer by $$$1\,000\,000\,007$$$.
standard output
PASSED
3b4a1e113bbf7fa2cc341cd1756461cf
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } static int[] a; static int n, p; static boolean ok(int i) { if (i == n) { return true; } for (int j = 0; j < p; ++j) { a[i] = j; if ((i < 1 || a[i - 1] != j) && (i < 2 || a[i - 2] != j)) { if (ok(i + 1)) return true; } } return false; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); n = nextInt(); p = nextInt(); String s = next(); a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = s.charAt(i) - 'a'; } for (int i = n - 1; i >= 0; --i) { while (a[i] + 1 < p) { ++a[i]; boolean valid = true; if (i > 0 && a[i - 1] == a[i]) { valid = false; } if (i > 1 && a[i - 2] == a[i]) { valid = false; } if (valid) { if (ok(i + 1)) { for (int j = 0; j < n; ++j) { out.print((char)('a' + a[j])); } out.println(); out.close(); System.exit(0); } } } } out.println("NO"); out.close(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
2db02a0585f509068ce95dc410ff2d2b
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class CopyOfD265_C { public static void main(String[] args) throws IOException { solve(); } static void solve() throws IOException { BufferedReader in; PrintWriter out; try { in = new BufferedReader(new FileReader("are1231a.in")); out = new PrintWriter(new File("are2131a.out")); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } StringTokenizer tok = new StringTokenizer(in.readLine()); int n = Integer.valueOf(tok.nextToken()); int p = Integer.valueOf(tok.nextToken())-1; String str = in.readLine(); char[] st = new char[n+2]; boolean ok = true; st[0] = 999; st[1] = 999; for (int i = 2; i < n+2; i++) { st[i] = str.charAt(i-2); } char tmp = 'a'; for (int i = n+1; i >= 2; i--) { tmp = st[i]; tmp++; while (tmp == st[i-1] | tmp == st[i-2]) tmp++; if ((tmp - 'a') > p) { continue; } st[i] = tmp; for (int j = i+1; j < n+2; j++) { st[j] = 'a'; while (st[j] == st[j-1] | st[j] == st[j-2]) st[j]++; if ((st[j] - 'a') > p) { ok = false; break; } } if (ok) { for (int k = 2; k < n+2; k++) { out.print(st[k]); } out.flush(); out.close(); return; } } out.println("NO"); out.close(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
5e92a320f8e1b26e8f1338b0edc56ff0
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.StringTokenizer; import javax.print.attribute.DocAttributeSet; import javax.print.attribute.HashDocAttributeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { boolean[] is_prime; int max; public void sieve(){ max = (1<<29)+(1<<27)+(1<<24)+(1<<23); //System.out.println(max); is_prime = new boolean[max+1]; is_prime[0] = is_prime[1] = true; for(int i = 2; i*i < max; i++){ if(!is_prime[i]){ for(int j = i*i; j <= max; j+=i){ is_prime[j] = true; } } } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt() , p = in.nextInt(); char[] s = in.next().toCharArray(); for(int i = n - 1; i >= 0; i--){ for(char ch = (char) (s[i]+1); ch < 'a'+p; ch++){ s[i] = ch; if( i >= 1 && s[i] == s[i-1] || i >= 2 && s[i] == s[i-2]) continue; lable: for(int j = i+1; j < n; j++){ for(char sd = 'a'; sd < 'a'+p; sd++){ s[j] = sd; if( j >= 1 && s[j] == s[j-1] || j >= 2 && s[j] == s[j-2]) continue; continue lable; } } out.println(new String(s)); return; } } out.println("NO"); } } //||||||| UNION FIND |||||||| class uni_find{ int[] id , sz; int count ; public uni_find(int N){ count = N; id = new int[N]; sz = new int [N]; for (int i = 0; i < N; i++) id[i] = i; for (int i = 0; i < N; i++) sz[i] = 1; } private int find(int p) { while (p != id[p]) p = id[p]; return p; } public void union(int p, int q) { int i = find(p); int j = find(q); if (i == j) return; // Make smaller root point to larger one. if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } count--; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } } //||||||| comparable pair |||||||| class pair implements Comparable<pair>{ public long first,second; public pair(){ first = second = 0; } @Override public int compareTo(pair arg0) { if(this.second > arg0.second) return 1; else if(this.second < arg0.second) return -1; else if(this.first > arg0.first) return 1; else if(this.first < arg0.first) return -1; return 0; } } // ||||||| INPUT READER |||||||| class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public Integer 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()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(Integer i = 0; i < n; i++) a[i] = nextInt(); return a; } public Long[] nextLongArray(int n) { Long[] a = new Long[n]; for(Integer i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextlongArray(int n) { long[] a = new long[n]; for(Integer i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextdoubleArray(int n) { double[] a = new double[n]; for(Integer i = 0; i < n; i++) a[i] = nextDouble(); return a; } public String[] nextStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } public String[] nextLineStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
8eb41d66468c8d26d7ea49f3398f144e
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Program { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static final int MOD = 1000000007; static final double INF = 10000000000.0; void solve() throws IOException { int n, p; n = nextInt(); p = nextInt(); char[] s = new char[n]; s = nextString().toCharArray(); boolean found = false; for(int i = n-1; i >= 0; i--) { for(int j = s[i]-'a'+1; j < p && !found; j++) { if (i > 0 && s[i-1]-'a' == j) continue; if (i > 1 && s[i-2]-'a' == j) continue; found = true; s[i] = (char)('a'+j); } if (found) { for(int j = i+1; j < n; j++) for(char k = 'a'; k <= 'z'; k++) { if (j > 0 && s[j-1] == k) continue; if (j > 1 && s[j-2] == k) continue; s[j] = k; break; } break; } } if (!found) out.println("NO"); else out.println(s); } Program() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new Program(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } class Pair implements Comparable<Pair>{ char first; int second; public Pair(char an1, int an2){ first = an1; second = an2; } @Override public int compareTo(Pair o) { if (first - o.first == 0) return second - o.second; else return first - o.first; } } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
5b874ec4c8d434e98a7dfc0905df23e4
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNext()) { int n = cin.nextInt(), p = cin.nextInt(); String s = cin.next(); char[] ch = s.toCharArray(); int[] a = new int[1001]; for (int i = 0; i < n; i++) { a[i] = ch[i] - 'a'; } if (p == 1) System.out.println("NO"); else { boolean find = false; for (int i = n - 1; i >= 0 && !find; i--) { for (int j = a[i] + 1; j < p && !find; j++) { if ((i < 1 || j != a[i - 1]) && (i < 2 || j != a[i - 2])) { a[i] = j; for (int j2 = i + 1; j2 < n; j2++) { a[j2] = 0; while ((j2 >= 1 && a[j2] == a[j2 - 1]) || (j2 >= 2 && a[j2] == a[j2 - 2])) a[j2]++; if (a[j2] == p) { System.out.println("NO"); return; } } find = true; } } } System.out.println(find ? convert(a, n) : "NO"); } } cin.close(); } private static String convert(int[] a, int n) { StringBuilder str = new StringBuilder(); for (int i = 0; i < n; i++) { str.append((char) (a[i] + 'a')); } return str.toString(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
033b92f24c1a7f7d553c69c97bc44fc1
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class ProblemA { public static void main(String[] args) throws Exception { int n = nextInt()-1; int p = nextInt(); String s = nextString(); char[] ch = s.toCharArray(); char upperBound = (char)('a'+p-1); while (n >= 0) { ch[n]++; if (ch[n] > upperBound) { n--; continue; } if (n > 0 && ch[n] == ch[n-1]) { continue; } else if (n > 1 && ch[n] == ch[n-2]) { continue; } if (fixUpRestOfString(ch, n, upperBound)) { System.out.println(String.valueOf(ch)); return; } } System.out.println("NO"); } private static boolean fixUpRestOfString(char[] ch, int n, char upperBound) { for (int i = n+1; i < ch.length; i++) { boolean valid = false; for (char c = 'a'; c <= upperBound; c++) { ch[i] = c; if (ch[i] != ch[i-1] && (i <= 1 || ch[i] != ch[i-2])) { valid = true; break; } } if (!valid) { return false; } } return true; } private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st = new StringTokenizer(""); private static String nextString() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } private static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
c7136aff6fff90bd6021e2e583b52be1
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
public class A { public A () { int N = sc.nextInt(); int P = sc.nextInt(); char [] C = sc.nextChars(); if (!inc (C, N-1, P)) exit("NO"); while (test(C, P) == 0); if (test(C, P) == 1) print(new String(C)); else print("NO"); } int test(char [] C, int P) { int N = C.length; for (int i : rep(2, N)) if (C[i] == C[i-1] || C[i] == C[i-2]) { boolean ok = inc(C, i, P); if (ok) return 0; else return 2; } return 1; } boolean inc(char [] C, int i, int P) { int N = C.length; char Z = (char)('a' + P - 1); do if (C[i] < Z) ++C[i]; else if (i == 0) return false; else return inc(C, i-1, P); while ((i >= 1 && C[i] == C[i-1]) || (i >= 2 && C[i] == C[i-2])); if (i+1 < N) { char x, y, z; for (x = 'a'; x <= 'c'; ++x) if (x != C[i] && (i == 0 || x != C[i-1])) break; for (y = 'a'; y <= 'c'; ++y) if (y != x && y != C[i]) break; for (z = 'a'; z <= 'c'; ++z) if (z != x && z != y) break; char [] Q = { x, y, z }; int q = 0; for (int j : rep(i+1, N)) C[j] = Q[(q++)%3]; } return true; } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void print (Object o, Object ... A) { IOUtils.print(o, A); } private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public char [] nextChars() { return next ().toCharArray (); } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim(String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new java.text.DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ... A) { pw.println(build(o, A)); } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } } public static void main (String[] args) { new A(); IOUtils.exit(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
44e11266eeb2f0a1ec78382db9f41d1b
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF265_Palindromes { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int strLen = in.nextInt(); int nLetters = in.nextInt(); char[] initStr = in.next().toCharArray(); char[] res = null; for (int i = initStr.length - 1; i >= 0; i--) { res = completePal(i, Arrays.copyOf(initStr, initStr.length), (char) ((char) 'a' + (nLetters - 1))); if (res != null) { break; } } if (res != null) { System.out.println(String.valueOf(res)); } else { System.out.println("NO"); } } public static char[] completePal(int startInd, char[] initPal, char maxChar) { outerLoop: for (int i = startInd; i < initPal.length; i++) { char startChar = 'a'; if (i == startInd) { startChar = (char) (initPal[startInd] + 1); } for (char c = startChar; c <= maxChar; c++) { if ((i < 1 || initPal[i - 1] != c) && (i < 2 || initPal[i - 2] != c)) { initPal[i] = c; continue outerLoop; } } return null; } return initPal; } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
36b0ac818484d54024a6a1b1380175e3
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.*; import java.util.*; public class CF { FastScanner in; PrintWriter out; void solve() { int n = in.nextInt(); int p = in.nextInt(); char[] a = in.next().toCharArray(); for (int i = n - 1; i >= 0; i--) { int now = 1 + a[i] - 'a'; while (now < p) { boolean ok = true; char nowC = (char) ('a' + now); if (i > 0 && a[i - 1] == nowC) ok = false; if (i > 1 && a[i - 2] == nowC) ok = false; if (ok) { a[i] = nowC; for (int j = i + 1; j < n; j++) { for (int k = 0; k < p; k++) { nowC = (char) ('a' + k); boolean ok2 = true; if (j > 0 && a[j - 1] == nowC) ok2 = false; if (j > 1 && a[j - 2] == nowC) ok2 = false; if (ok2) { a[j] = nowC; break; } } } for (int j = 0; j < n; j++) { out.print(a[j]); } return; } now++; } } out.println("NO"); } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new CF().runIO(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
a861df7fb9933f1777009a20f9c3538d
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { ///////////////////////////////////////////////////////////// public void solve(int testNumber, FastScanner in, FastPrinter out) { int n=in.nextInt(),p=in.nextInt(); int[] a= new int[n]; String s=in.next(); for (int i = 0; i < n; i++) { a[i]= s.charAt(i)-'a'; } try{ boolean tt=true; int pos=n-1,c=1; while (tt){ while (c>0){ a[pos]+=c; c=0; if (a[pos]>=p){a[pos]-=p; c=1; } pos--; } tt=false; for (int i = 0; i < n - 1; i++) { if (a[i]==a[i+1]){ tt=true; pos=i+1; c=1; break; } if (i+2<n&&a[i]==a[i+2]){ tt=true; pos=i+2; c=1; break; } } } for (int i = 0; i < n; i++) { out.print((char) ('a' + a[i])); } out.println(); } catch (Exception e){ out.println("NO"); } } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
61f8534952b9f8856dec082a6f312ad4
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { // 689^*( public void solve(int testNumber, FastScanner in, FastPrinter out) { int n=in.nextInt(),p=in.nextInt(); String s=in.next(); int[] a= new int[n]; for (int i = 0; i < n; i++) { a[i]=s.charAt(i)-'a'; } int pos=n-1; boolean chk=false; while (pos>=0&&pos<n){ if (chk){ chk=false; } else a[pos]++; if (a[pos]==p){ a[pos]=0; pos--; continue; } if (pos>0&&a[pos]==a[pos-1])continue; if (pos>1&&a[pos]==a[pos-2])continue; pos++; chk=true; } if (pos<0) out.println("NO"); else{ StringBuilder sb= new StringBuilder(); for (int i = 0; i < n; i++) { sb.append((char)(a[i]+'a')); } out.println(sb.toString()); } } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
5fa4a0ca7c1082d25a45fd9a4d79ecd6
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { new Solution().solve(); } int n, p; char a[]; String s; char temp; public void solve() { reader.init(new InputStreamReader(System.in)); n = reader.nextInt(); p = reader.nextInt(); s = reader.next(); a = new char[n + 1]; for (int i = 1; i <= n; i++) { a[i] = s.charAt(i - 1); } int x = n; while (!canInc(x)){ x--; if (x == 0) { System.out.print("NO"); return; } } a[x] = temp; for (int j = x + 1; j <= n; j++) { for (char k = 'a'; k < 'a' + p; k++) { if (k != a[j-1] && k != a[j-2]) { a[j] = k; break; } } } for (int i = 1; i <= n; i++) { System.out.print(a[i]); } } public boolean canInc(int x) { if (a[x] - 'a' >= p - 1) return false; if (x == 1) { temp = (char) (a[x] + 1); return true; } if (x == 2) { for (char i = (char) (a[x] + 1); i < 'a' + p; i++) { if (i != a[1]) { temp = i; return true; } } } for (char i = (char) (a[x] + 1); i < 'a' + p; i++) { if (i != a[x - 1] && i != a[x - 2]) { temp = i; return true; } } return false; } } class reader { static BufferedReader br; static StringTokenizer st; public static void init(Reader in) { br = new BufferedReader(in); st = new StringTokenizer(""); } public static String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f801d52139fb405ec0063bafcc12e52a
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.*; import java.util.*; public class A { BufferedReader in; StringTokenizer st; PrintWriter out; String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } String getNext(String st, int a) { int n = st.length(); char s[] = st.toCharArray(); for (int i = n - 1; i >= 0; i--) { boolean fl = false; for (int j = s[i] - 'a' + 1; j < a && !fl; j++) { // if ((i == 0) && (j == a - 1)) // return "NO"; if ((i <= 0) || ((j + 'a') != s[i - 1])) if ((i <= 1) || ((j + 'a') != s[i - 2])) { s[i] = (char) (j + 'a'); fl = true; } } if (fl) { for (int k = i + 1; k < n; k++) { boolean found = false; for (int j = 0; j < a && !found; j++) { //System.err.println(k + " => " + (char) (j + 'a')); if ((k <= 0) || ((j + 'a') != s[k - 1])) if ((k <= 1) || ((j + 'a') != s[k - 2])) { found |= true; s[k] = (char) (j + 'a'); } } } String ans = new String(s); return ans; } } return "NO"; } void solve() throws Exception { int n = nextInt(), a = nextInt(); String st = next(); out.println(getNext(st, a)); } void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new A().run(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
1ae0b9b4a114b073535dbf0928a48387
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class ProblemA { boolean[] palin; char[] cs; private ProblemA() throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); String h = rd.readLine(); String[] q = h.split("\\s+"); int p = Integer.parseInt(q[1]); String s = rd.readLine(); cs = s.toCharArray(); palin = new boolean[p]; int n = s.length(); int pos = n-1; char last = ((char)('a'+(p-1))); boolean dir = false; while(true) { if(pos < 0) { out("NO"); return; } if(pos > n-1) { out(new String(cs)); return; } constructPalin(pos); if(dir) { boolean filled = false; for(char j='a';j<=last;j++) { if(!palin[j-'a']) { cs[pos] = j; filled = true; break; } } if(filled) { pos++; } else { pos--; dir = false; } } else { for(char j=((char)(cs[pos]+1));j<=last;j++) { if(!palin[j-'a']) { cs[pos] = j; dir = true; pos++; break; } } if(!dir) { pos--; } } } } private void constructPalin(int pos) { Arrays.fill(palin, false); for(int j = pos-1;j>=0;j--) { int k = 1; int len = pos-j+1; int check = (len-2)/2; boolean ok = true; while(ok && k <= check) { if(cs[j+k] != cs[pos-k]) { ok = false; } k++; } if(ok) { palin[cs[j]-'a']=true; } } } private static void out(Object x) { System.out.println(x); } public static void main(String[] args) throws IOException { new ProblemA(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
70824988fed99d4fbbf63c69e7ff2615
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.Scanner; public class NotoPalindromes { public static String check(String s, int n, int p) { for (int i = 0; i < s.length(); i++) { if (i >= 1 && s.charAt(i) == s.charAt(i - 1)) return null; if (i >= 2 && s.charAt(i) == s.charAt(i - 2)) return null; } if (s.length() == n) return s; // if (n == 2) { // if (s.charAt(0) == 'a') // return "ba"; // else // return null; // } StringBuilder sb = new StringBuilder(s); while (sb.length() < n) { for (char c = 'a'; c <= 'c'; c++) { if (sb.length() >= 1 && sb.charAt(sb.length() - 1) == c) continue; else if (sb.length() >= 2 && sb.charAt(sb.length() - 2) == c) continue; else { sb.append(c); break; } } } return sb.toString(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int p = sc.nextInt(); String s = sc.next(); for (int i = s.length() - 1; i >= 0; i--) { String prefx = s.substring(0, i); for (char ch = (char) (s.charAt(i) + 1); ch < 'a' + p; ch++) { String res = check(prefx + ch, n, p); if (res != null) { System.out.println(res); return; } } } System.out.println("NO"); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
e8ded4f891bfc983431589ffea227177
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int p = nextInt(); char[]a = next().toCharArray(); for (int i = n-1; i >= 0; i--) { if (a[i]-96 != p) { int k = a[i]-96; for (int j = k+1; j <= p; j++) { a[i] = (char)(j+96); boolean ok = true; if (i != 0 && a[i]==a[i-1]) ok = false; else { if (i > 1 && a[i]==a[i-2]) ok = false; else { for (int j2 = i+1; j2 < n; j2++) { boolean found = false; for (int l = 1; l <= p; l++) { boolean can = true; if (l==a[j2-1]-96) can = false; if (j2 > 1 && l==a[j2-2]-96) can = false; if (can) { a[j2] = (char)(l+96); found = true; break; } } if (!found) { ok = false; break; } } } } if (ok) { for (int j2 = 0; j2 < n; j2++) { System.out.print(a[j2]); } System.out.println(); return; } } } } System.out.println("NO"); pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
792cd7284a01ea74f1da7833cc4b94b1
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.*; import java.io.*; public class A { public static PrintStream out = System.out; public static InputReader in = new InputReader(System.in); public static void main(String args[]) { int N, P; N = in.nextInt(); P = in.nextInt(); String S = in.next(); char[] c = S.toCharArray(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = (int) (c[i] - 'a'); } int i = N - 1; while (true) { if (i == -1) { out.println("NO"); System.exit(0); } a[i]++; outer : while (true) { if (a[i] >= P) break; if ((i >= 2 && a[i - 2] == a[i]) || (i >= 1 && a[i - 1] == a[i])) { a[i]++; continue outer; } break; } if (a[i] >= P) i--; else break; } for (int j = i + 1; j < N; j++) { for (int k = 0; k < P; k++) { if (!(j >= 2 && a[j - 2] == k) && !(j >= 1 && a[j - 1] == k)) { a[j] = k; break; } } } char[] fc = new char[N]; for (i = 0; i < N; i++) { fc[i] = (char) (a[i] + 'a'); } out.println(new String(fc)); } } 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 double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
37bf2287965be533e71e1ba05e7e2c89
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int P = nextInt(); String S = reader.readLine(); int[] C = new int[N]; for (int i = 0; i < S.length(); i++) { C[i] = S.charAt(i) - 'a'; } int firstIndex = -1; outer: for (int i = N-1; i >= 0; i--) { for (int j = C[i]+1; j < P; j++) { boolean OK = true; if (i > 0 && j == C[i-1]) OK = false; if (i > 1 && j == C[i-2]) OK = false; if (OK) { firstIndex = i; C[i] = j; break outer; } } } if (firstIndex == -1) { out.println("NO"); return; } for (int i = firstIndex+1; i < N; i++) { for (int j = 0; j < P; j++) { boolean OK = true; if (i > 0 && j == C[i-1]) OK = false; if (i > 1 && j == C[i-2]) OK = false; if (OK) { C[i] = j; break; } } } StringBuilder ans = new StringBuilder(); for (int i = 0; i < N; i++) { ans.append( (char)('a' + C[i])); } out.println(ans.toString()); } /** * @param args */ public static void main(String[] args) { new A().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
c9b80f640276ae57215b40a0d29cde5e
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { private int N, K; private char[] S; private boolean Solve(int pos) { if (pos == N) return false; if (Solve(pos + 1)) return true; ++S[pos]; while (S[pos] - 'a' < K && ((pos > 0 && S[pos] == S[pos - 1] || (pos > 1 && S[pos] == S[pos - 2])))) ++S[pos]; if (S[pos] - 'a' == K) return false; for (int i = pos + 1; i < N; ++i) { int j; for (j = 0; (i > 0 && j + 'a' == S[i - 1]) || (i > 1 && j + 'a' == S[i - 2]); ++j); if (j >= K) return false; S[i] = (char) (j + 'a'); } return true; } public void solve(int testNumber, InputReader in, PrintWriter out) { N = in.nextInt(); K = in.nextInt(); S = in.nextString().toCharArray(); if (Solve(0)) out.println(new String(S)); else out.println("NO"); } } 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 nextInt() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
11438dcc04c4a6060b9c7fa4c4e50951
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { void solve() throws IOException { int n=nextInt(); int p=nextInt(); String s=nextToken(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=s.charAt(i)-'a'; boolean good=false; for(int i=n-1;i>=0;i--){ int ind=-1; for(int j=a[i]+1;j<p;j++){ if(!(i>0&&j==a[i-1]||i>1&&j==a[i-2])){ ind=j; break; } } if(ind!=-1) { int[] prev=Arrays.copyOf(a,n); a[i]=ind; boolean q=true; for(int j=i+1;j<n;j++){ int x=-1; for(int k=0;k<p;k++) if(a[j-1]!=k&&!(j>1&&a[j-2]==k)){ x=k; break; } if(x==-1){ q=false; break; } else{ a[j]=x; } } if(!q)a=prev; else{ good=true; break; } } } if(good) for(int i=0;i<n;i++) out.print((char)('a'+a[i])); else out.println("NO"); } public static void main(String[] args) throws IOException { new A().run(); } void run() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); // reader = new BufferedReader(new FileReader("input.txt")); tokenizer = null; out = new PrintWriter(new OutputStreamWriter(System.out)); // out = new PrintWriter(new FileWriter("output.txt")); solve(); reader.close(); out.flush(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
81c92db31fe5793a3ce585a3c81c10fb
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class NoToPalindromes464A { static void go() { int n = in.nextInt(); int p = in.nextInt(); String str = in.nextString(); int[] s = new int[n + 3]; for (int i = 0; i < n; i++) s[i + 2] = str.charAt(i) - 'a'; s[0] = s[1] = -1; boolean valid = false; for (int i = s.length - 2; i >= 2; i--) { for (int ch = s[i] + 1; ch < p; ch++) { if (s[i - 1] != ch && s[i - 2] != ch) { s[i] = ch; if (nextSuffix(s, i + 1, p)) { printStr(s); return; } } } } out.println("NO"); } static boolean nextSuffix(int[] s, int index, int max) { for (int i = index; i < s.length-1; i++) { boolean valid = false; for (int ch = 0; ch < max; ch++) { if (s[i - 1] != ch && s[i - 2] != ch) { s[i] = ch; valid = true; break; } } if (!valid) return false; } return true; } static void printStr(int[] s) { char[] ch = new char[s.length - 3]; for (int i = 0; i < ch.length; i++) ch[i] = (char) ('a' + s[i + 2]); out.println(ch); } 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
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
3364f62a07f4701c8c80bc242182a1cb
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.*; import java.io.*; //question code: public class A implements Runnable { public void solve() throws IOException { int N = nextInt(), K = nextInt(); char[] a = nextToken().toCharArray(); for(int i = N-1; i >= 0; i--){ for(char c ='a' ; c < 'a' + K; c++){ if(c > a[i]){ if(i == 0 || a[i-1] != c){ if(i <= 1 || a[i-2] != c){ a[i++] = c; while(i < N){ for(char now = 'a'; now <= 'c'; now++){ if(i >= 1 && a[i-1] == now) continue; if(i >= 2 && a[i-2] == now) continue; a[i++] = now; break; } } System.out.println(new String(a)); return; } } } } } System.out.print("NO"); } //----------------------------------------------------------- public static void main(String[] args) { new A().run(); } 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)); tok = null; solve(); in.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()); } BufferedReader in; StringTokenizer tok; }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f8130ebdbe2cd40a8735d40c999f5992
train_000.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
//AntiPalindrome.java import java.util.*; public class AntiPalindrome{ private static String resultString; private static boolean foundResult; private static boolean palindrome; private static int N,P; private static String aString; private static int palindromeIndex; private static final int BASENUM = 97; private static final int NUMCHAR = 26; private static final String ALPHASTRING = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int index; String s; boolean reachEndOfString; palindrome = true; palindromeIndex = -1; aString = ""; N = sc.nextInt(); P = sc.nextInt(); s = sc.next(); for(int i=0;i<N;i++){ aString+="a"; } index = s.length()-1; update(s,index); if(foundResult){ System.out.println(resultString); } else{ System.out.println("NO"); } } private static void update(String s, int index){ int updateCharIndex; char updateChar; updateCharIndex = (s.charAt(index)-BASENUM+1)%NUMCHAR; while((updateCharIndex>=P||updateCharIndex==0) && index!=0){ index--; updateCharIndex = (s.charAt(index)-BASENUM+1)%NUMCHAR; } if(index==0&&(updateCharIndex>=P||updateCharIndex==0)){ foundResult = false; } else{ s = s.substring(0,index)+ALPHASTRING.charAt(updateCharIndex)+s.substring(index+1); // s.replace(index,ALPHASTRING.charAt(updateCharIndex)); int replaceLength = s.length()-(index+1); s=s.substring(0,index+1)+aString.substring(0,replaceLength); // for(int i=index+1;i<s.length();i++){ // s = s.substring(0,i)+'a'+s.substring(i+1); // } if(isPalindrome(s,index)){ update(s,palindromeIndex); } else{ foundResult = true; } } } // private static boolean isPalindrome(String s,int index){ // int prevInstanceIndex = -1; // int arrowLeft,arrowRight; // boolean potentialPalindrome = true; // palindromeIndex = index; // if(index>=s.length()){ // resultString = s; // return false; // } // for(int i=index+1;i>=0&&prevInstanceIndex!=-1;i--){ // if(s.charAt(i)==s.charAt(index)){ // prevInstanceIndex = i; // } // } // if(prevInstanceIndex!=-1){ // prevChar is beside currChar // if(prevInstanceIndex==(index-1)){ // return true; // } // else{ // // checking a---><---a // arrowLeft = prevInstanceIndex; // arrowRight = index; // potentialPalindrome=true; // while((arrowLeft<arrowRight)&&potentialPalindrome){ // potentialPalindrome = s.charAt(arrowLeft)==s.charAt(arrowRight); // arrowLeft++; // arrowRight--; // // } // if(potentialPalindrome){ // return true; // } // if(prevInstanceIndex==0){ // return isPalindrome(s,index+1); // } // else{ // checking |<---a<---a // arrowLeft = prevInstanceIndex; // arrowRight = index; // potentialPalindrome = true; // while(((arrowRight>prevInstanceIndex)||(arrowLeft<0))&&potentialPalindrome){ // potentialPalindrome = s.charAt(arrowRight)==s.charAt(arrowLeft); // arrowLeft--; // arrowRight--; // } // if(potentialPalindrome){ // return true; // } // } // // } // // } // return isPalindrome(s,index+1); // } private static boolean isPalindrome(String s, int index){ palindrome = false; char currChar = s.charAt(index); char nextChar, prevChar,grandPrevChar; nextChar = prevChar = ' '; if(index==0){ //ignore } else if(index== 1){ palindrome = s.charAt(0)==currChar; } else{ prevChar = s.charAt(index-1); grandPrevChar = s.charAt(index-2); palindrome = currChar ==prevChar || currChar == grandPrevChar; } if(!palindrome){ if(index==(s.length()-1)){ resultString = s; return palindrome; } else{ return isPalindrome(s,index+1); } } else{ palindromeIndex = index; return palindrome; } } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 7
standard input
[ "greedy", "strings" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
ec44c9e26481ba76a5cfed39006f342f
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.stream.Stream; import java.util.Map; import java.util.Collection; import java.util.Map.Entry; import java.util.Scanner; import java.util.Optional; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main( String[] args ) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner( inputStream ); PrintWriter out = new PrintWriter( outputStream ); TaskC solver = new TaskC(); solver.solve( 1, in, out ); out.close(); } static class TaskC { public void solve( int testNumber, Scanner in, PrintWriter out ) { int n = in.nextInt(); Map<Integer, Integer> xs = new HashMap<>(); Map<Integer, Integer> ys = new HashMap<>(); Map<String, Integer> repetions = new HashMap<>(); for( int i = 0; i < n; i++ ) { int x = in.nextInt(); int y = in.nextInt(); repetions.merge( x + " " + y, 1, ( a, b ) -> a + b ); xs.merge( x, 1, ( a, b ) -> a + b ); ys.merge( y, 1, ( a, b ) -> a + b ); } long result = 0; result += xs.entrySet().stream() .filter( p -> p.getValue() > 1 ) .map( p -> combinations( p.getValue() ) ) .reduce( ( a, b ) -> a + b ).orElse( 0L ); result += ys.entrySet().stream() .filter( p -> p.getValue() > 1 ) .map( p -> combinations( p.getValue() ) ) .reduce( ( a, b ) -> a + b ).orElse( 0L ); result -= repetions.entrySet().stream() .filter( p -> p.getValue() > 1 ) .map( p -> combinations( p.getValue() ) ) .reduce( ( a, b ) -> a + b ).orElse( 0L ); out.print( result ); } public static long combinations( int n ) { return (long) n * ( n - 1 ) / 2; } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
b1ccf9203ab960e56259ca5a050bc862
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.*; public class Watchmen { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); Map<Long, Integer> X = new HashMap<>(); Map<Long, Integer> Y = new HashMap<>(); Map<Map<Long,Long>,Integer> XY = new HashMap<>(); int n = scan.nextInt(); for(int i=0;i<n;i++) { Long x = scan.nextLong(); Long y = scan.nextLong(); Map<Long,Long> temp = new HashMap<>(); temp.put(x, y); X.put(x,X.getOrDefault(x, 0)+1); Y.put(y, Y.getOrDefault(y, 0)+1); XY.put(temp, XY.getOrDefault(temp,0)+1); } long pairs = 0; for(Map.Entry<Long, Integer> l1 : X.entrySet()) { long v = l1.getValue(); pairs+=v*(v-1)/2; } for(Map.Entry<Long,Integer> l2: Y.entrySet()) { long v = l2.getValue(); pairs+=v*(v-1)/2; } for(Map.Entry<Map<Long,Long>, Integer> l3: XY.entrySet()) { long v = l3.getValue(); pairs-=v*(v-1)/2; } System.out.println(pairs); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
6ec247606f390aa04bb47b0f5f4c47d2
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.*; public class Watchmen1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); Map<Long, Integer> X = new HashMap<>(); Map<Long, Integer> Y = new HashMap<>(); Map<Map<Long,Long>,Integer> XY = new HashMap<>(); int n = scan.nextInt(); for(int i=0;i<n;i++) { Long x = scan.nextLong(); Long y = scan.nextLong(); Map<Long,Long> temp = new HashMap<>(); temp.put(x, y); X.put(x,X.getOrDefault(x, 0)+1); Y.put(y, Y.getOrDefault(y, 0)+1); XY.put(temp, XY.getOrDefault(temp,0)+1); } long pairs = 0; for(Map.Entry<Long, Integer> l1 : X.entrySet()) { long v = l1.getValue(); pairs+=v*(v-1)/2; } for(Map.Entry<Long,Integer> l2: Y.entrySet()) { long v = l2.getValue(); pairs+=v*(v-1)/2; } for(Map.Entry<Map<Long,Long>, Integer> l3: XY.entrySet()) { long v = l3.getValue(); pairs-=v*(v-1)/2; } System.out.println(pairs); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
f8d7fd60bf34412a1cce0cf2d0aba396
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Watchmen { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); int num=in.nextInt(); Map<Long,Integer> X=new HashMap<>(); Map<Long,Integer> Y=new HashMap<>(); Map<Map<Long,Long>,Integer> XY=new HashMap<>(); for(int i=0;i<num;i++) { Long x=in.nextLong(); Long y=in.nextLong(); Map<Long,Long> temp=new HashMap<>(); temp.put(x, y); X.put(x, X.getOrDefault(x, 0)+1); Y.put(y, Y.getOrDefault(y, 0)+1); XY.put(temp, XY.getOrDefault(temp, 0)+1); } long pairs=0; for(Map.Entry<Long, Integer> el:X.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Long, Integer> el:Y.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Map<Long,Long>, Integer> el:XY.entrySet()) { long value=el.getValue(); pairs=pairs-value*(value-1)/2; } System.out.println(pairs); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
0f6d62b4179da3f4fbcb121b25235bb9
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); Map<Integer, Integer> xMap, yMap; Map<Pair<Integer, Integer>, Integer> p; xMap = new HashMap<>(); yMap = new HashMap<>(); p = new HashMap<>(); long ans = 0; long same = 0; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); put(xMap, x); put(yMap, y); Pair<Integer, Integer> pair = new Pair<>(x, y); putSame(p, pair); } for (long num : xMap.values()) { ans += num * (num - 1) / 2; } for (long num : yMap.values()) { ans += num * (num - 1) / 2; } for (long num : p.values()) { ans -= num * (num - 1) / 2; } out.println(ans); out.flush(); in.close(); out.close(); } private static void put(Map<Integer, Integer> map, int key) { int now = map.getOrDefault(key, 0); map.put(key, now + 1); } private static void putSame(Map<Pair<Integer, Integer>, Integer> map, Pair<Integer, Integer> key) { int now = map.getOrDefault(key, 0); map.put(key, now + 1); } static class Reader { BufferedReader reader; StringTokenizer st; Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } void close() throws IOException { reader.close(); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() throws IOException { return reader.readLine(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
080e330e8655a58a567d54c49bea28a2
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.awt.Point; import java.io.*; import java.util.*; import java.math.BigInteger; public class Watchmen { static class Solver { MyReader mr = new MyReader(); public void solve() { int n = mr.nextInt(); Map<Integer,Integer> xm = new HashMap<>(); Map<Integer,Integer> ym = new HashMap<>(); Map<Point,Integer> pp = new HashMap<>(); long sim = 0; for (int i = 0; i < n; i++) { int x = mr.nextInt(); int y = mr.nextInt(); xm.put(x, xm.getOrDefault(x,0) + 1); ym.put(y, ym.getOrDefault(y,0) + 1); Point p = new Point(x,y); pp.put(p, pp.getOrDefault(p,0) + 1); } long res = 0; for (long v : xm.values()){ res += (v*(v-1))/2; } for (long v : ym.values()){ res += (v*(v-1))/2; } for (long v : pp.values()){ res -= (v*(v-1))/2; } // System.out.println(xm); // System.out.println(ym); // System.out.println(pp); System.out.println(res); } } public static void main(String[] args) { new Solver().solve(); } static class MyReader { BufferedReader br; StringTokenizer st; MyReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception 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 res = ""; try { res = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return res; } Integer[] nextIntArray(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } Long[] nextLongArray(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } String[] nextStringArray(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = next(); } return arr; } } static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
be7edad50fb9351a0a19bf557a9e4f9d
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.awt.*; import java.util.*; /** * Created by maxim on 3/12/16. */ public class C651 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long res = 0; HashMap<Integer, Integer> xCoords = new HashMap<>(); HashMap<Integer, Integer> yCoords = new HashMap<>(); HashMap<Point, Integer> points = new HashMap<>(); while(n-->0) { int x = sc.nextInt(), y = sc.nextInt(); Point p = new Point(x, y); if (!xCoords.containsKey(x)) { xCoords.put(x, 0); } if (!yCoords.containsKey(y)) { yCoords.put(y, 0); } if (!points.containsKey(p)) { points.put(p, 0); } res += xCoords.get(x) + yCoords.get(y) - points.get(p); xCoords.put(x, xCoords.get(x) + 1); yCoords.put(y, yCoords.get(y) + 1); points.put(p, points.get(p) + 1); } System.out.println(res); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
63341deb109ef7afdbd22826bae87575
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class c651 { public static void main(String[] args) { // TODO Auto-generated method stub HashMap<Integer, Integer> xs = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> ys = new HashMap<Integer,Integer>(); HashMap<Point,Integer> locs = new HashMap<Point,Integer>(); Scanner in = new Scanner(System.in); long count = 0; int n = in.nextInt(); for(int i = 0; i < n; i++){ int x = in.nextInt(); int y = in.nextInt(); Point p = new Point(x,y); if(xs.containsKey(x)){ count+=xs.get(x); xs.put(x, xs.remove(x)+1); }else{ xs.put(x, 1); } if(ys.containsKey(y)){ count+=ys.get(y); ys.put(y, ys.remove(y)+1); }else{ ys.put(y, 1); } if(locs.containsKey(p)){ count-=locs.get(p); locs.put(p, locs.remove(p)+1); }else{ locs.put(p, 1); } } System.out.println(count); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
c76a30d7978610e5aed7979d8705c590
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Watchmen { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); int num=in.nextInt(); Map<Long,Integer> X=new HashMap<>(); Map<Long,Integer> Y=new HashMap<>(); Map<Map<Long,Long>,Integer> XY=new HashMap<>(); for(int i=0;i<num;i++) { Long x=in.nextLong(); Long y=in.nextLong(); Map<Long,Long> temp=new HashMap<>(); temp.put(x, y); X.put(x, X.getOrDefault(x, 0)+1); Y.put(y, Y.getOrDefault(y, 0)+1); XY.put(temp, XY.getOrDefault(temp, 0)+1); } long pairs=0; for(Map.Entry<Long, Integer> el:X.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Long, Integer> el:Y.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Map<Long,Long>, Integer> el:XY.entrySet()) { long value=el.getValue(); pairs=pairs-value*(value-1)/2; } System.out.println(pairs); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
69b762a66e99314a5980963ffe96db52
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt();// n~2e5 Set<Point> p = new HashSet<>(); Map<Point, Integer> dup = new HashMap<>(); Map<Integer, Integer> xco = new HashMap<>(); Map<Integer, Integer> yco = new HashMap<>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); Point np = new Point(x, y); int xo = 0, yo = 0; if (!p.contains(np)) { p.add(np); } else { if (!dup.containsKey(np)) dup.put(np, 2); else dup.put(np, dup.get(np) + 1); } if (xco.containsKey(x)) xo = xco.get(x); if (yco.containsKey(y)) yo = yco.get(y); xco.put(x, xo + 1); yco.put(y, yo + 1); } long count = 0;// count~2e~10 for (int xv : xco.keySet()) { long occ = xco.get(xv); count += occ * (occ - 1) / 2; } for (int yv : yco.keySet()) { long occ = yco.get(yv); count += occ * (occ - 1) / 2; } for (Point dp : dup.keySet()) { long dcy = dup.get(dp); count -= dcy * (dcy - 1) / 2; } System.out.println(count); sc.close(); } static class Point { int x; int y; public Point(int a, int b) { x = a; y = b; } @Override public boolean equals(Object obj) { Point p2 = (Point) obj; return this.x == p2.x && this.y == p2.y; } @Override public int hashCode() { // // int max~2.1e9 // int x2 = (x >= 0) ? 2 * x : -2 * x + 1;//x2~2e9 // int y2 = (y >= 0) ? 2 * y : -2 * y + 1;//y2~2e9 // long hc=(x2 + y2 + 1) * (x2 + y2) / 2 + x2; // return //~8e18 int hash = 7; hash = 71 * hash + this.x; hash = 71 * hash + this.y; return hash; } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
180cddff2b166fa70f5704ce27c5e1e8
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.*; public class main { public static void main(String agrs[]) { Scanner in = new Scanner (System.in); int numofwatchmen=in.nextInt(); long output=0; Map<String,Integer> xy=new HashMap<>(); Map<Integer ,Integer>x=new HashMap<>(); Map<Integer ,Integer>y=new HashMap<>(); for (int i=0;i<numofwatchmen;i++) { int x1=in.nextInt(); int y1=in.nextInt(); String s=x1+""+y1; if (x.containsKey(x1)){ int xi=x.get(x1); x.put(x1, xi+1); } else { x.put(x1, 1); } if (y.containsKey(y1)){ int yi=y.get(y1); y.put(y1, yi+1); } else { y.put(y1, 1); } if (xy.containsKey(s)){ int yi=xy.get(s); xy.put(s, yi+1); } else { xy.put(s, 1); } } for (Integer value : x.values()) { long add= (long) Math.pow(value, 2); add=add-value; add=add/2; output +=add; } for (Integer value : y.values()) { long add= (long) Math.pow(value, 2); add=add-value; add=add/2; output +=add; } for (Integer value : xy.values()) { long add= (long) Math.pow(value, 2); add=add-value; add=add/2; output =output-add; } System.out.println(output); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
40ceea3b13c8a227c53c742b17c70cfb
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
/* * import java.util.*; public class Manhattan_euclid { */ /*// public static void main(String[] args) { // // TODO Auto-generated method stub // Scanner sc=new Scanner(System.in); // int n=sc.nextInt(); // Pair1 arr[]=new Pair1[n]; // HashMap<Long,Integer> h1=new HashMap<>(); // HashMap<Long,Integer> h2=new HashMap<>(); // HashMap<Pair1,Integer> h3=new HashMap<>(); // for(int i=0;i<n;i++) // { // long x=sc.nextLong(); // long y=sc.nextLong(); // // if(h1.containsKey(x)) // h1.put(x,h1.get(x)+1); // else // h1.put(x, 1); // // if(h2.containsKey(y)) // h2.put(y,h2.get(y)+1); // else // h2.put(y, 1); // // // if(h3.containsKey(new Pair1(x,y))) // h3.put(new Pair1(x,y),h3.get(new Pair1(x,y))+1); // else // h3.put(new Pair1(x,y), 1); // } // // long ans=0; // for(Map.Entry<Long, Integer> i:h1.entrySet()) // { // int v=i.getValue(); // ans+=(v*(v-1))/2; // } // // for(Map.Entry<Long, Integer> i:h2.entrySet()) // { // int v=i.getValue(); // ans+=(v*(v-1))/2; // } // // for(Map.Entry<Pair1, Integer> i:h3.entrySet()) // { // int v=i.getValue(); // ans-=(v*(v-1))/2; // } // // System.out.println(ans); // } // // static class Pair1 // { // long x,y; // public Pair1(long x,long y) // { // this.x=x; // this.y=y; // } // // @Override // public boolean equals(Object o) // { // if(this==o) // { // return true; // } // // if(!(o instanceof Pair1)) // return false; // Pair1 p=(Pair1) o; // // return x==p.x && y==p.y; // } // // public int hashCode() // { // long result = x; // result = 2 * result + y; // return (int)(result); // } // } }*/ import java.util.*; public class Manhattan_euclid { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Pair1 arr[]=new Pair1[n]; HashMap<Long,Long> h1=new HashMap<>(); HashMap<Long,Long> h2=new HashMap<>(); HashMap<HashMap<Long,Long>,Long> h3=new HashMap<>(); long sum=1; for(int i=0;i<n;i++) { long x=sc.nextLong(); long y=sc.nextLong(); if(h1.containsKey(x)) h1.put(x,h1.get(x)+(long)1); else h1.put(x, sum); if(h2.containsKey(y)) h2.put(y,h2.get(y)+(long)1); else h2.put(y, sum); HashMap<Long,Long> h4=new HashMap<>(); h4.put(x,y); if(h3.containsKey(h4)) h3.put(h4,h3.get(h4)+(long)1); else h3.put(h4, sum); } long ans=0; for(Map.Entry<Long, Long> i:h1.entrySet()) { long v=i.getValue(); ans+=(v*(v-1))/2; } for(Map.Entry<Long, Long> i:h2.entrySet()) { long v=i.getValue(); ans+=(v*(v-1))/2; } for(Map.Entry<HashMap<Long,Long>, Long> i:h3.entrySet()) { long v=i.getValue(); ans-=(v*(v-1))/2; } System.out.println(ans); } static class Pair1 { long x,y; public Pair1(long x,long y) { this.x=x; this.y=y; } @Override public boolean equals(Object o) { if(this==o) { return true; } if(!(o instanceof Pair1)) return false; Pair1 p=(Pair1) o; return x==p.x && y==p.y; } public int hashCode() { long result = x; result = 2 * result - y; return (int)(result%100000000); } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
2f692bd83e6bc26b51b7a39f065d1319
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
/* * import java.util.*; public class Manhattan_euclid { */ /*// public static void main(String[] args) { // // TODO Auto-generated method stub // Scanner sc=new Scanner(System.in); // int n=sc.nextInt(); // Pair1 arr[]=new Pair1[n]; // HashMap<Long,Integer> h1=new HashMap<>(); // HashMap<Long,Integer> h2=new HashMap<>(); // HashMap<Pair1,Integer> h3=new HashMap<>(); // for(int i=0;i<n;i++) // { // long x=sc.nextLong(); // long y=sc.nextLong(); // // if(h1.containsKey(x)) // h1.put(x,h1.get(x)+1); // else // h1.put(x, 1); // // if(h2.containsKey(y)) // h2.put(y,h2.get(y)+1); // else // h2.put(y, 1); // // // if(h3.containsKey(new Pair1(x,y))) // h3.put(new Pair1(x,y),h3.get(new Pair1(x,y))+1); // else // h3.put(new Pair1(x,y), 1); // } // // long ans=0; // for(Map.Entry<Long, Integer> i:h1.entrySet()) // { // int v=i.getValue(); // ans+=(v*(v-1))/2; // } // // for(Map.Entry<Long, Integer> i:h2.entrySet()) // { // int v=i.getValue(); // ans+=(v*(v-1))/2; // } // // for(Map.Entry<Pair1, Integer> i:h3.entrySet()) // { // int v=i.getValue(); // ans-=(v*(v-1))/2; // } // // System.out.println(ans); // } // // static class Pair1 // { // long x,y; // public Pair1(long x,long y) // { // this.x=x; // this.y=y; // } // // @Override // public boolean equals(Object o) // { // if(this==o) // { // return true; // } // // if(!(o instanceof Pair1)) // return false; // Pair1 p=(Pair1) o; // // return x==p.x && y==p.y; // } // // public int hashCode() // { // long result = x; // result = 2 * result + y; // return (int)(result); // } // } }*/ import java.util.*; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Manhattan_euclid { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); int num=in.nextInt(); Map<Long,Integer> X=new HashMap<>(); Map<Long,Integer> Y=new HashMap<>(); Map<Map<Long,Long>,Integer> XY=new HashMap<>(); for(int i=0;i<num;i++) { Long x=in.nextLong(); Long y=in.nextLong(); Map<Long,Long> temp=new HashMap<>(); temp.put(x, y); X.put(x, X.getOrDefault(x, 0)+1); Y.put(y, Y.getOrDefault(y, 0)+1); XY.put(temp, XY.getOrDefault(temp, 0)+1); } long pairs=0; for(Map.Entry<Long, Integer> el:X.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Long, Integer> el:Y.entrySet()) { long value=el.getValue(); pairs=pairs+value*(value-1)/2; } for(Map.Entry<Map<Long,Long>, Integer> el:XY.entrySet()) { long value=el.getValue(); pairs=pairs-value*(value-1)/2; } System.out.println(pairs); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
e62c59caec44ff5bc682e8e60415f780
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import javafx.util.Pair; import java.util.HashMap; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); long answer=0; HashMap<Integer, Integer> x = new HashMap<>(); HashMap<Integer, Integer> y = new HashMap<>(); HashMap<Pair<Integer, Integer>,Integer> diff = new HashMap<>(); for(int i=0;i<n;i++) { int xtemp = s.nextInt(); int ytemp = s.nextInt(); x.put(xtemp,x.getOrDefault(xtemp,0)+1); y.put(ytemp,y.getOrDefault(ytemp,0)+1); diff.put(new Pair<>(xtemp,ytemp),diff.getOrDefault(new Pair<>(xtemp,ytemp),0)+1); } for (int x1:x.keySet() ) { answer+=sum(x.getOrDefault(x1,1)-1); } for (int y1:y.keySet() ) { answer+=sum(y.getOrDefault(y1,1)-1); } for(int i :diff.values()){ answer-= sum(i-1); } System.out.println(answer); } static long sum(int x) { long temp=0; for(int i=1;i<=x;i++ ) temp+=i; return temp; } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
dc6d2d6721750916489a5ef63277091c
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static final boolean FILE_IO = false; static StringTokenizer st; static BufferedReader in; static PrintWriter out; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; else st = new StringTokenizer(str); } return st.nextToken(); } static class Coord { public int x, y; public Coord(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coord coord = (Coord) o; if (x != coord.x) return false; return y == coord.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // -- Map<Integer, Integer> horizontal = new HashMap<>(); Map<Integer, Integer> vertical = new HashMap<>(); Map<Coord, Integer> coords = new HashMap<>(); int n = nextInt(); // for (int i = 0; i < n; i++) { Coord c = new Coord(nextInt(), nextInt()); add(coords, c); add(horizontal, c.x); add(vertical, c.y); } long result = 0; for (Map.Entry<Integer, Integer> a : horizontal.entrySet()) { int m = a.getValue(); result += (long) m * (m - 1) / 2; } for (Map.Entry<Integer, Integer> a : vertical.entrySet()) { int m = a.getValue(); result += (long) m * (m - 1) / 2; } for (Map.Entry<Coord, Integer> a : coords.entrySet()) { int m = a.getValue(); if (m != 1) { result -= (long) m * (m - 1)/2; } } out.print(result); // -- out.flush(); out.close(); } private static void add(Map<Coord, Integer> coords, Coord c) { if (!coords.containsKey(c)) { coords.put(c, 1); } else { coords.put(c, coords.get(c) + 1); } } private static void add(Map<Integer, Integer> coords, Integer c) { if (!coords.containsKey(c)) { coords.put(c, 1); } else { coords.put(c, coords.get(c) + 1); } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
8c8796044bcf8e026466380952ceba6f
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
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.HashMap; import java.util.StringTokenizer; import java.util.TreeSet; public class A { static class Pair implements Comparable<Pair>{ int x, y; public Pair(int a, int b){ x = a; y = b; } @Override public int compareTo(Pair o) { if(x == o.x) return y - o.y; return x - o.x; } } public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(); Pair [] inp = new Pair[n]; TreeSet<Integer> y = new TreeSet<>(); HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) { inp[i] = new Pair(bf.nextInt(), bf.nextInt()); y.add(inp[i].y); } int c = 0; for(int i:y) mp.put(i, c++); int [] occ = new int[y.size()]; Arrays.sort(inp); long ans = 0; int tmp = 0; for (int i = 0; i < inp.length; i++) { c = 1; for(;i+1 < inp.length && inp[i].compareTo(inp[i+1]) == 0;i++, c++); ans += 1L*c*(c-1)/2; ans += 1L*c*(tmp); ans += 1L*c*(occ[mp.get(inp[i].y)]); occ[mp.get(inp[i].y)] += c; if(i+1 < n && inp[i+1].x == inp[i].x) tmp += c; else tmp = 0; } out.println(ans); 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
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
b5391afa302cc5cb5d13e3eb1c0d0708
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author you */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); WatchmenInCF solver = new WatchmenInCF(); solver.solve(1, in, out); out.close(); } static class WatchmenInCF { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); Map<Integer, Integer> hmx = new HashMap<>(); Map<Integer, Integer> hmy = new HashMap<>(); Map<WatchmenInCF.Pair<Integer, Integer>, Integer> hmp = new HashMap<>(); while (n-- > 0) { int x = in.nextInt(); int y = in.nextInt(); if (!hmx.keySet().contains(x)) { hmx.put(x, 1); } else { hmx.put(x, hmx.get(x) + 1); } if (!hmy.keySet().contains(y)) { hmy.put(y, 1); } else { hmy.put(y, hmy.get(y) + 1); } WatchmenInCF.Pair<Integer, Integer> coord = new WatchmenInCF.Pair<>(x, y); if (!(hmp.keySet().contains(coord))) { hmp.put(coord, 1); } else { hmp.put(coord, hmp.get(coord) + 1); } } long sum = 0; long sub = 0; for (long num : hmx.values()) { sum += num * (num - 1) / 2; } for (long num : hmy.values()) { sum += num * (num - 1) / 2; } for (long num : hmp.values()) { sub += num * (num - 1) / 2; } out.println(sum - sub); } static class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<WatchmenInCF.Pair<S, T>> { S first; T second; Pair(S f, T s) { first = f; second = s; } public int compareTo(WatchmenInCF.Pair<S, T> o) { int t = first.compareTo(o.first); if (t == 0) return second.compareTo(o.second); return t; } public int hashCode() { // return Long.hashCode((long) 1e9 * first.hashCode() + second.hashCode()); return (31 + first.hashCode()) * 31 + second.hashCode(); } public boolean equals(Object o) { if (!(o instanceof WatchmenInCF.Pair)) return false; if (o == this) return true; WatchmenInCF.Pair p = (WatchmenInCF.Pair) o; return first.equals(p.first) && second.equals(p.second); } public String toString() { return "Pair{" + first + ", " + second + "}"; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
c1038e4732c8af8da61e82b1ab95b5d0
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author you */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); WatchmenInCF solver = new WatchmenInCF(); solver.solve(1, in, out); out.close(); } static class WatchmenInCF { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); Map<Integer, Integer> hmx = new HashMap<>(); Map<Integer, Integer> hmy = new HashMap<>(); Map<WatchmenInCF.Pair<Integer, Integer>, Integer> hmp = new HashMap<>(); while (n-- > 0) { int x = in.nextInt(); int y = in.nextInt(); if (!hmx.keySet().contains(x)) { hmx.put(x, 1); } else { hmx.put(x, hmx.get(x) + 1); } if (!hmy.keySet().contains(y)) { hmy.put(y, 1); } else { hmy.put(y, hmy.get(y) + 1); } WatchmenInCF.Pair<Integer, Integer> coord = new WatchmenInCF.Pair<>(x, y); if (!(hmp.keySet().contains(coord))) { hmp.put(coord, 1); } else { hmp.put(coord, hmp.get(coord) + 1); } } long sum = 0; long sub = 0; for (long num : hmx.values()) { sum += num * (num - 1) / 2; } for (long num : hmy.values()) { sum += num * (num - 1) / 2; } for (long num : hmp.values()) { sub += num * (num - 1) / 2; } out.println(sum - sub); } static class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<WatchmenInCF.Pair<S, T>> { S first; T second; Pair(S f, T s) { first = f; second = s; } public int compareTo(WatchmenInCF.Pair<S, T> o) { int t = first.compareTo(o.first); if (t == 0) return second.compareTo(o.second); return t; } public int hashCode() { return Long.hashCode((long) 1e9 * first.hashCode() + second.hashCode()); // return (31 + first.hashCode()) * 31 + second.hashCode(); } public boolean equals(Object o) { if (!(o instanceof WatchmenInCF.Pair)) return false; if (o == this) return true; WatchmenInCF.Pair p = (WatchmenInCF.Pair) o; return first.equals(p.first) && second.equals(p.second); } public String toString() { return "Pair{" + first + ", " + second + "}"; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
bbe61e59f26ee489fef97ed5109a7da0
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author Don Li */ public class Watchmen { static final int N = (int) 2e9 + 7; void solve() { int n = in.nextInt(); Map<Long, Long> xMap = new HashMap<>(), yMap = new HashMap<>(), xyMap = new HashMap<>(); for (int i = 0; i < n; i++) { long x = in.nextInt(), y = in.nextInt(), xy = x * N + y; if (!xMap.containsKey(x)) xMap.put(x, 1L); else xMap.put(x, xMap.get(x) + 1); if (!yMap.containsKey(y)) yMap.put(y, 1L); else yMap.put(y, yMap.get(y) + 1); if (!xyMap.containsKey(xy)) xyMap.put(xy, 1L); else xyMap.put(xy, xyMap.get(xy) + 1); } long ans = 0; for (long x : xMap.values()) ans += x * (x - 1) / 2; for (long x : yMap.values()) ans += x * (x - 1) / 2; for (long x : xyMap.values()) ans -= x * (x - 1) / 2; out.println(ans); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new Watchmen().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
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
92e88ff551576fde49e4e3528ecd2169
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class Problem_03 { public static void main(String[] args) throws Exception { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); HashMap<Integer, Integer> x = new HashMap<>(n + n); HashMap<Integer, Integer> y = new HashMap<>(n + n); HashMap<Long, Integer> same = new HashMap<>(n + n); for (int i = 0; i < n; i++) { String[] l = input.readLine().split(" "); int xc = Integer.parseInt(l[0]); int yc = Integer.parseInt(l[1]); Integer xcount = x.get(xc); Integer ycount = y.get(yc); x.put(xc, xcount == null ? 1 : xcount + 1); y.put(yc, ycount == null ? 1 : ycount + 1); long s = (1000000001 + (long)xc) * 2000000002 + (1000000001 + (long)yc); Integer sm = same.get(s); same.put(s, sm == null ? 1 : sm + 1); } long sum = 0; for (int xcount : x.values()) { if (xcount > 1) { sum += ((long)xcount * ((long)xcount - 1)) / 2; } } for (int ycount : y.values()) { if (ycount > 1) { sum += ((long)ycount * ((long)ycount - 1)) / 2; } } for (int sm : same.values()) { if (sm > 1) { sum -= ((long)sm * ((long)sm - 1)) / 2; } } System.out.println(sum); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
236fb3c87ac00368387cc00df065c39d
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { new C().run(); } Scanner in; public void run() { try { in = new Scanner(System.in); solve(); } catch (Exception e) { } } class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; return y == pair.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } public void solve() { int n = in.nextInt(); HashMap<Integer, Long> x = new HashMap<>(); HashMap<Integer, Long> y = new HashMap<>(); HashMap<Pair, Long> coor = new HashMap<>(); long ans = 0; for (int i = 0; i < n; i++) { int c1 = in.nextInt(); int c2 = in.nextInt(); int pairs = 0; if (x.containsKey(c1)) { pairs += x.get(c1); } if (y.containsKey(c2)) { pairs += y.get(c2); } ans += pairs; if (!x.containsKey(c1)) { x.put(c1, 0L); } if (!y.containsKey(c2)) { y.put(c2, 0L); } x.put(c1, x.get(c1) + 1); y.put(c2, y.get(c2) + 1); Pair cur = new Pair(c1, c2); if (!coor.containsKey(cur)) { coor.put(cur, 0L); } coor.put(cur, coor.get(cur) + 1); } for (Map.Entry<Pair, Long> entry : coor.entrySet()) { ans -= entry.getValue() * (entry.getValue() - 1) / 2; } System.out.println(ans); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
88a187b85d9339ede02f72175c3495f8
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); long counter = 0; Map<Long, Integer> xMap = new HashMap<>(); Map<Long, Integer> yMap = new HashMap<>(); Map<String, Integer> sameMap = new HashMap<>(); for (int i = 0; i < n; i++) { long xKey = scanner.nextLong(); long yKey = scanner.nextLong(); xMap.put(xKey, xMap.getOrDefault(xKey, 0) + 1); yMap.put(yKey, yMap.getOrDefault(yKey, 0) + 1); String sameKey = "" + xKey + yKey; sameMap.put(sameKey, sameMap.getOrDefault(sameKey, 0) + 1); } scanner.close(); for (Map.Entry<Long, Integer> x : xMap.entrySet()) { int value = x.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<Long, Integer> y : yMap.entrySet()) { int value = y.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<String, Integer> same : sameMap.entrySet()) { int value = same.getValue(); counter -= (long) value * ((long) value - 1) / 2; } System.out.println(counter); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
b7544b5cb5cc9fee7d7a43d733a9bc05
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); long counter = 0; Map<Long, Integer> xMap = new HashMap<>(); Map<Long, Integer> yMap = new HashMap<>(); Map<String, Integer> sameMap = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { long xKey = scanner.nextLong(); long yKey = scanner.nextLong(); xMap.put(xKey, xMap.getOrDefault(xKey, 0) + 1); yMap.put(yKey, yMap.getOrDefault(yKey, 0) + 1); String sameKey = "" + xKey + yKey; sameMap.put(sameKey, sameMap.getOrDefault(sameKey, 0) + 1); } scanner.close(); for (Map.Entry<Long, Integer> x : xMap.entrySet()) { int value = x.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<Long, Integer> y : yMap.entrySet()) { int value = y.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<String, Integer> same : sameMap.entrySet()) { int value = same.getValue(); counter -= (long) value * ((long) value - 1) / 2; } System.out.println(counter); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
cebac2854cc9a8f0ee03afa443165796
train_000.jsonl
1457342700
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i &lt; j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); long counter = 0; Map<Long, Integer> xMap = new HashMap<>(); Map<Long, Integer> yMap = new HashMap<>(); Map<String, Integer> sameMap = new TreeMap<>(); for (int i = 0; i < n; i++) { long xKey = scanner.nextLong(); long yKey = scanner.nextLong(); xMap.put(xKey, xMap.getOrDefault(xKey, 0) + 1); yMap.put(yKey, yMap.getOrDefault(yKey, 0) + 1); String sameKey = "" + xKey + yKey; sameMap.put(sameKey, sameMap.getOrDefault(sameKey, 0) + 1); } scanner.close(); for (Map.Entry<Long, Integer> x : xMap.entrySet()) { int value = x.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<Long, Integer> y : yMap.entrySet()) { int value = y.getValue(); counter += (long)value * ((long)value - 1) / 2; } for (Map.Entry<String, Integer> same : sameMap.entrySet()) { int value = same.getValue(); counter -= (long) value * ((long) value - 1) / 2; } System.out.println(counter); } }
Java
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
3 seconds
["2", "11"]
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Java 8
standard input
[ "data structures", "geometry", "implementation", "sortings" ]
bd7b85c0204f6b36dc07f8a96fc36161
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000)Β β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide.
1,400
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
standard output
PASSED
7416a75ba97e4010e0a242821df8d487
train_000.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≀ li ≀ ri ≀ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class Main { static class Reader { BufferedReader r; StringTokenizer str; Reader() { r=new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { r=new BufferedReader(new FileReader(fileName)); } public String getNextToken() throws IOException { if(str==null||!str.hasMoreTokens()) { str=new StringTokenizer(r.readLine()); } return str.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(getNextToken()); } public long nextLong() throws IOException { return Long.parseLong(getNextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(getNextToken()); } public String nextString() throws IOException { return getNextToken(); } public int[] intArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] longArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public String[] stringArray(int n) throws IOException { String a[]=new String[n]; for(int i=0;i<n;i++) a[i]=nextString(); return a; } public int gcd(int a, int b) { if(b == 0){ return a; } return gcd(b, a%b); } } static int bits=32; public static void main(String args[]) throws IOException{ Reader r=new Reader(); PrintWriter pr=new PrintWriter(System.out,false); char a[]=r.nextString().toCharArray(); int n=a.length; int m=r.nextInt(); int tree[][]=new int[4*n][3]; construct(a,tree,1,0,n-1); int x,y;long z; for(int i=0;i<m;i++) { x=r.nextInt()-1; y=r.nextInt()-1; pr.println(query(tree,1,0,n-1,x,y)[0]); } pr.flush(); pr.close(); } public static void construct(char a[],int tree[][], int root,int l ,int r) { if(l==r) { tree[root][0]=0; if(a[l]=='(') tree[root][1]=1; else tree[root][2]=1; return; } construct(a,tree,root<<1,l,(l+r)>>1); construct(a,tree,(root<<1)+1,((l+r)>>1)+1,r); tree[root][0]+=tree[root<<1][0]+tree[(root<<1)+1][0]+2*(Math.min(tree[root<<1][1],tree[(root<<1)+1][2])); tree[root][1]+=tree[root<<1][1]+tree[(root<<1)+1][1]-Math.min(tree[root<<1][1],tree[(root<<1)+1][2]); tree[root][2]+=tree[root<<1][2]+tree[(root<<1)+1][2]-Math.min(tree[root<<1][1],tree[(root<<1)+1][2]); // System.out.println(root+" "+stack[root]); } static int[] query(int tree[][],int root,int l,int r,int begin,int end) { if(begin>r||end<l) return new int[]{0,0,0}; if(begin<=l&&r<=end) { return tree[root]; } return add(query(tree,root<<1,l,(l+r)>>1,begin,end),query(tree,(root<<1)+1,((l+r)>>1)+1,r,begin,end)); } public static int[] add(int a[],int b[]) { int c[]=new int[3]; c[0]=a[0]+b[0]+(2*Math.min(a[1],b[2])); c[1]=a[1]+b[1]-Math.min(a[1],b[2]); c[2]=a[2]+b[2]-Math.min(a[1],b[2]); return c; } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≀ k1 &lt; k2 &lt; ... &lt; k|x| ≀ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Β«()Β».For the fourth query required sequence will be Β«()(())(())Β».
Java 7
standard input
[ "data structures" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≀ n ≀ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≀ li ≀ ri ≀ n) β€” the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
ca618e6945945eaef17483027b9bc29a
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class B { public static void main(String[] args) { FastReader in = new FastReader(); TreeSet<Integer> list = new TreeSet<>(); int n = in.nextInt(), k = in.nextInt(); for (int i = 0; i < n; i++) { int a = in.nextInt(); if (a == 0) continue; list.add(a); } int sum = 0, c = 0; for (int i : list) { if (c >= k) break; System.out.println(i - sum); sum += i - sum; c++; } if (c < k) { int[] last = new int[k - c]; System.out.println(Arrays.toString(last).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n")); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
a64cf6133f0ff9de48ae514934100552
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.TreeSet; public class B { public static void main(String[] args) throws IOException { Reader in = new Reader(); TreeSet<Integer> list = new TreeSet<>(); int n = in.nextInt(), k = in.nextInt(); for (int i = 0; i < n; i++) { int a = in.nextInt(); if (a == 0) continue; list.add(a); } in.close(); int sum = 0, c = 0; for (int i : list) { if (c >= k) break; System.out.println(i - sum); sum += i - sum; c++; } if (c < k) { int[] last = new int[k - c]; System.out.println(Arrays.toString(last).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n")); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
586bf5e60ed770019f78407404f17ff4
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; public class subtraction { void solve()throws IOException { /**************** write your code here ***********************/ int n=ni(),k=ni();int s=0,c=0,r=0,id=0; long a[]=na(n); sort(a,0,n-1);long cnt=0; for(int i=1;i<=k;i++) { while(id<n && a[id]<=cnt) id++; if(id==n) { cnt=a[id-1]; System.out.println(0); continue; } System.out.println(a[id]-cnt); cnt =a[id]; } } static void merge(long arr[], int l, int m, int r) { // Find sizes of two subtractionarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subtractionarrays int i = 0, j = 0; // Initial index of merged subtractionarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void main(String[] args)throws IOException { new subtraction().solve(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; InputStream is=System.in; 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 long[] na(int n) { long[] a = new long[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
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
a1c417845d2c7865b2cf1fc0054e0408
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.io.*; import java.util.*; public class yay { public static int mod(int a, int b){ return (a%b + b)%b; } public static long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; int count1 = 1; for(int i = 0;i<n;i++) { arr[i] = sc.nextInt(); } Arrays.sort(arr); out.println(arr[0]); int count = arr[0]; int count2 = 0; int a = k; for(int i = 1;i<n;i++) { if(arr[i]-count>0&&i<=k-1) { out.println(arr[i]-count); count += arr[i]-count; } if(i<=k&&arr[i]==arr[i-1]) { k++; count1--; } count1++; } for(int i = count1;i<a;i++) { out.println(0); } out.close(); } }
Java
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
b98b5c83eb5b7391867f477e6375e7ea
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class B { public static void main(String [ ] args) { int n, k; int[] list = new int[100001]; Scanner inn = new Scanner(System.in); n = inn.nextInt(); k = inn.nextInt(); for(int i = 0; i < n; i++) { list[i] = inn.nextInt(); } Arrays.sort(list, 0, n); int index = 0; System.out.println(list[index]); k--; while(k > 0) { if(index + 1 >= n) { System.out.println(0); k--; index++; } else { while(index + 1 < n && list[index] == list[index + 1]) { index++; } if(index + 1 >= n) { System.out.println(0); k--; index++; } else if(list[index] != list[index + 1]) { System.out.println(list[index + 1] - list[index]); k--; index++; } } } } }
Java
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
edadd7c0a897ef9cdd087abfa5e8daae
train_000.jsonl
1543934100
You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static int i,j,k,l,temp,count; public static void main(String[] args) throws IOException{ /* . . . . . . */ int n=ni(); int k=ni(); int arr[]=nia(n); Arrays.sort(arr); i=0; temp=0; while(k>0 && i<n){ arr[i] -= temp; temp += arr[i]; if(arr[i]!=0){ sop(arr[i]); k--; } i++; } while(k>0){ sop(0); k--; } /* . . . . . . . */ } static int gcd(int a,int b){ if(a==0) return b; return gcd(b%a,a); } static int arr[]=new int[100002]; static int front=0; static int rear=-1; static void offer(int data){ arr[front]=data; front++; } static int peek(){ return arr[rear+1]; } static boolean isEmpty(){ if(rear+1==front){ return true; } else return false; } static int poll(){ rear++; return arr[rear]; } /* fuctions . . . . . . . . . . . . . . . . . abcdefghijklmnopqrstuvwxyz . . . . . . */ static int modulo(int j,int m){ if(j<0) return m+j; if(j>=m) return j-m; return j; } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static final boolean debug=true; static Reader in=new Reader(); static StringBuilder ans=new StringBuilder(); static long powm(long a,long b,long m){ long an=1; long c=a; while(b>0){ if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static Random rn=new Random(); static void sop(Object a){System.out.println(a);} static int ni(){return in.nextInt();} static int[] nia(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=ni();return a;} static long nl(){return in.nextLong();} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String ns(){return in.next();} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double nd(){return in.nextDouble();} static double[] nda(int n){double a[]=new double[n];for(int i=0;i<n;i++)a[i]=nd();return a;} static class Reader{ public BufferedReader reader; public StringTokenizer tokenizer; public Reader(){ reader=new BufferedReader(new InputStreamReader(System.in),32768); tokenizer=null; } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try{ tokenizer=new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["3 5\n1 2 3", "4 2\n10 3 5 3"]
1 second
["1\n1\n1\n0\n0", "3\n2"]
NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.
Java 8
standard input
[ "implementation", "sortings" ]
0f100199a720b0fdead5f03e1882f2f3
The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.
1,000
Print the minimum non-zero element before each operation in a new line.
standard output
PASSED
cf25a037732c2dfca52b68957d316054
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for (int o=0;o<T;o++){ String ss = scan.next(); String cc = scan.next(); String[] s = ss.split(""); String[] c = cc.split(""); if (ss.compareTo(cc)<0){ System.out.println(ss); } else{ for (int i=0;i<s.length-1;i++){ int index = i; for (int j=s.length-1;j>i;j--){ if (s[index].compareTo(s[j])>0){ index = j; } } if (index!=i){ String temp = s[i]; s[i] = s[index]; s[index] = temp; break; } } String str = String.join("",s); int A = str.compareTo(String.join("", c)); if (A<0){ System.out.println(str); } else{ System.out.println("---"); } } } } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
81d239a5aad547445f8d88890746766d
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
//package contest1281; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class B { private final FastReader fastReader = new FastReader(); private void swap(char[] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } private boolean findLexicographicallySmall(String s, String c) { for (int i = 0; i < s.length() && i < c.length(); i++) { if (s.charAt(i) < c.charAt(i)) { return true; } else if (s.charAt(i) == c.charAt(i)) { continue; } else { return false; } } return s.length() < c.length() ? true : false; } private void solve() { String s = fastReader.next(); String c = fastReader.next(); if (findLexicographicallySmall(s, c)) { System.out.println(s); return; } char[] as = s.toCharArray(); Arrays.sort(as); int i = 0; while (i < s.length()) { if (s.charAt(i) == as[i]) { i++; continue; } else break; } var s2 = s.toCharArray(); if (i < s.length()) { char temp = as[i]; int j = s.lastIndexOf(temp); swap(s2, i, j); } var result = new String(s2); if (findLexicographicallySmall(result, c)) { System.out.println(result); } else { System.out.println("---"); } } private void run() { int tt = fastReader.nextInt(); while (tt-- != 0) { solve(); } } public static void main(String[] args) { new B().run(); } private static class FastReader { private final BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public FastReader() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException ioException) { ioException.getMessage(); } } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
4dbd32654c3ad3accd5ba015b0afaa1e
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static point a[]; static int check(int wx, int wy, int sx, int sy) { //waurma int cnt = 0; for (int i = 0; i < a.length; i++) { int x = a[i].x; int y = a[i].y; if (wx >= Math.min(sx, x) && wy >= Math.min(sy, y) && wx <= Math.max(sx, x) && wy <= Math.max(sy, y)) cnt++; } return cnt; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int q = nextInt(); while (q-- > 0) { char[] a = next().toCharArray(); char[] b = next().toCharArray(); boolean ans = false; for (int i = 0; i < Math.min(a.length, b.length); i++) { int ind = -1; for (int j = i; j < a.length; j++) { if (a[j] == b[i]) ind = j; if (a[j] < b[i]) { ind = j; ans = true; break; } } if (ans) { char t = a[i]; a[i] = a[ind]; a[ind] = t; break; } if (ind == -1) { break; } char t = a[i]; a[i] = a[ind]; a[ind] = t; if (a[ind] != a[i]) break; } String aa = ""; for (int i = 0; i < a.length; i++) { aa += a[i] + ""; } String bb = ""; for (int i = 0; i < b.length; i++) { bb += b[i] + ""; } if (aa.compareTo(bb) < 0) out.println(a); else out.println("---"); } out.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class point { int x, y; public point(int x, int y) { this.x = x; this.y = y; } } class cf { int value, x, y; public cf(int value, int x, int y) { this.value = value; this.x = x; this.y = y; } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
857bc01c58e4d17ab27b89520fb54e03
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.util.function.*; import java.util.function.Predicate; import java.math.BigInteger; import java.sql.Array; import java.time.Instant; import java.time.Duration; import java.util.concurrent.*; public class Main { static String swap(String s, int i, int j) { StringBuilder sb = new StringBuilder(s); sb.setCharAt(i, s.charAt(j)); sb.setCharAt(j, s.charAt(i)); return sb.toString(); } static String optimumSwap(String s) { char[] bestCharOnRightInc = new char[s.length()]; int[] bestIdxOnRightInc = new int[s.length()]; bestCharOnRightInc[s.length() - 1] = s.charAt(s.length() - 1); bestIdxOnRightInc[s.length() - 1] = s.length() - 1; for (int i = s.length() - 2; i >= 0; i--) { if (s.charAt(i) < bestCharOnRightInc[i + 1]) { bestCharOnRightInc[i] = s.charAt(i); bestIdxOnRightInc[i] = i; } else { bestCharOnRightInc[i] = bestCharOnRightInc[i + 1]; bestIdxOnRightInc[i] = bestIdxOnRightInc[i + 1]; } } for (int i = 0; i < s.length(); i++) { if (s.charAt(i) > bestCharOnRightInc[i]) { return swap(s, i, bestIdxOnRightInc[i]); } } // no swap was done. String already as small as it can be return s; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); // long startTime = System.nanoTime(); ///////////////////////////////////////////////////// int n = sc.nextInt(); for (int i = 0; i < n; i++) { String s = sc.next(); String c = sc.next(); if (s.compareTo(c) < 0) { System.out.println(s); } else { // do the optimum swap String swapped = optimumSwap(s); if (swapped.compareTo(c) >= 0) { System.out.println("---"); } else { System.out.println(swapped); } } } ///////////////////////////////////////////////////// // long endTime = System.nanoTime(); // System.out.printf("Executed in: %.2fms\n", ((double)endTime - startTime) / 1000000); sc.close(); } } class Pair { public int x; public int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { // System.out.println("inside equals"); if (o == this) { return true; } else if (!(o instanceof Pair)) { return false; } else { Pair p = (Pair)o; return this.x == p.x && this.y == p.y; } } @Override public int hashCode() { // System.out.println("inside hashcode"); return Arrays.hashCode(new int[]{this.x, this.y}); } @Override public String toString() { return "(" + this.x + ", " + this.y + ")"; } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
d070535ad5b42d8880e909d9b3e03b6c
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.util.*; import java.io.*; public class File { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int test = 0; test < t; test++) { char[] a = sc.next().toCharArray(); char[] b = sc.next().toCharArray(); a = getSmallest(a); if (isSmaller(a, b)) { System.out.println(new String(a)); } else { System.out.println("---"); } } } public static boolean isSmaller(char[] a, char[] b) { int i = 0; while (i < a.length && i < b.length) { if (a[i] == b[i]) { i++; } else { if (a[i] > b[i]) { return false; } else { return true; } } } // a is a prefix of b. if (i == a.length && i < b.length) { return true; } // a is longer than or same length as b. return false; } public static char[] getSmallest(char[] a) { int N = a.length; // precompute the smallest character to right of each index int[] smallestToRight = new int[N]; smallestToRight[N-1] = N-1; int currSmallest = N-1; for (int i = N - 2; i >= 0; i--) { smallestToRight[i] = currSmallest; if (a[i] < a[currSmallest]) { currSmallest = i; } } for (int i = 0; i < N; i++) { if (a[smallestToRight[i]] < a[i]) { swap(a, smallestToRight[i], i); break; } } return a; } public static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
7638121333b843cdf7b7a82a06028692
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class PairComparator implements Comparator<Pair> { @Override public int compare(Pair x, Pair y) { if (x.val < y.val)return -1; if (x.val > y.val)return 1; if (x.val == y.val){ if (x.ind < y.ind)return -1; if (x.ind > y.ind)return 1; } return 0; } } static class Pair{ int ind, val; Pair(int i, int v){ ind=i; val=v; } } static void func() throws Exception { String a,b; a= sc.next(); b= sc.next(); StringBuilder sb = new StringBuilder(a); char[] word = new char[a.length()]; int[] wordI = new int[a.length()]; word[a.length()-1] = a.charAt(a.length()-1); wordI[a.length()-1] = a.length()-1; for (int i=a.length()-2;i>=0;i--){ if (word[i+1]<=a.charAt(i)){ word[i] = word[i+1]; wordI[i] = wordI[i+1]; } else{ word[i] = a.charAt(i); wordI[i] = i; } } for (int i=0;i<a.length();i++){ if (a.charAt(i)>word[i]){ sb.setCharAt(i,word[i]); sb.setCharAt(wordI[i], a.charAt(i)); break; } } if (sb.toString().compareTo(b)>=0)pw.println("---"); else pw.println(sb.toString()); } static PrintWriter pw; static MScanner sc; public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new MScanner(System.in); int tests = 1; tests =sc.nextInt(); //comment this line while (tests-- > 0){ func(); pw.flush(); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i+1)); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i+1)); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
25d9a71710199044daa4a1cfa49eddc2
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Azamon { static PrintWriter out; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); for (int i = 0; i < t; i++) { String tmp = sc.next(); char[] p = tmp.toCharArray(); int n = p.length; tmp = sc.next(); char[] q = tmp.toCharArray(); int m = q.length; int[] smallerIndex = preprocess(p); boolean good = true; int j = 0; while (j < n) { if (m <= j) { good = false; break; } if (p[j] < q[j]) { break; } if (smallerIndex[q[j]-'A'] > j ) { swap(p, j, smallerIndex[q[j]-'A']); break; } if (p[j] > q[j]) { if (smallerIndex[q[j]-'A'+1] > j ) { swap(p, j, smallerIndex[q[j]-'A'+1]); break; } good = false; break; } j++; } if (good) while (j < n) { if (m<=j || p[j] > q[j]) { good = false; break; } if (p[j] < q[j]) { break; } j++; } if(new String(p).equals(new String(q))) good=false; out.println(good ? new String(p) : "---"); } sc.close(); out.close(); } private static void swap(char[] sb, int i, int j) { char tmp = sb[i]; sb[i] = sb[j]; sb[j] = tmp; } private static int[] preprocess(char[] p) { int len = 'Z' - 'A' + 1; int[] result = new int[len]; for (int i = 0; i < len; i++) { result[i] = -1; } for (int i = 0; i < p.length; i++) { char ch = p[i]; for (char j = (char) (ch + 1); j <= 'Z'; j++) { result[j - 'A'] = i; } } return result; } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
080a0031b3a60803caba0fca88bb4395
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BAzamonWebServices solver = new BAzamonWebServices(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BAzamonWebServices { PrintWriter out; InputReader in; public void solve(int testNumber, InputReader in, PrintWriter out) { this.out = out; this.in = in; char[] arr1 = n().toCharArray(); char[] arr2 = n().toCharArray(); char[] arr3 = Arrays.copyOf(arr1, arr1.length); Arrays.sort(arr3); int i = 0, j = 0; int n = arr1.length; int m = arr2.length; for (i = 0; i < n; i++) { if (arr1[i] != arr3[i]) { int ind = -1, mx = 'Z' + 1; for (j = i + 1; j < n; j++) { if (mx >= arr1[j]) { mx = arr1[j]; ind = j; } } char t = arr1[i]; arr1[i] = arr1[ind]; arr1[ind] = t; break; } } String st = "", st1 = ""; for (i = 0; i < n; i++) st += arr1[i]; for (i = 0; i < m; i++) st1 += arr2[i]; if (st.compareTo(st1) < 0) pn(st); else pn("---"); } String n() { return in.next(); } void pn(String zx) { out.println(zx); } } 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 UnknownError(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
42e3b3b993c4870645984046ea2616ed
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.*; import java.util.*; public class d2prac implements Runnable { private boolean console=false; public void solve(int t) { int i; char s[]=in.ns().toCharArray(); int n=s.length; char s1[]=in.ns().toCharArray(); for(i=0;i<n-1;i++) { char min=s[i]; int ind=-1; for(int j=n-1;j>=i+1;j--) { if(s[j]<min) { min=s[j]; ind =j; } } if(ind!=-1) { s[ind]=s[i]; s[i]=min; break; } } boolean ans=false; for(i=0;i<s.length;i++) { if(i==s1.length) break; if(s1[i]<s[i]) { ans=false; break; } if(s[i]<s1[i]) { ans=true; break; } } if(i==s.length&&s.length<s1.length) ans=true; if(ans) System.out.println(s); else System.out.println("---"); } @Override public void run() { try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } int t= in.ni(); int p=0; while (++p<=t) { solve(p); out.flush(); } } private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new d2prac().run(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (!console && System.getProperty("user.name").equals("sachan")) { outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt"); inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } static class FastInput { InputStream obj; public FastInput(InputStream obj) { this.obj = obj; } byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; } String ns() { int b = skip();StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();} 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(); }} 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 * 10L + (b - '0'); } else { return minus ? -num : num; }b = readByte(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; } float nf() {return Float.parseFloat(ns());} double nd() {return Double.parseDouble(ns());} char nc() {return (char) skip();} } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
aa0af7e9d0613524a35910c481b59a31
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.*; import java.util.*; public class B607{ public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ String st=sc.next(); String st2=sc.next(); if(st.compareTo(st2)<0){ System.out.println(st); } else{ char[] ch=st.toCharArray(); char[] ch1=st.toCharArray(); Arrays.sort(ch1); int i; int cnt2=0; for(i=0;i<ch.length;i++){ if(ch[i]!=ch1[i]){ break; } } if(i<ch.length){ int j; for(j=ch.length-1;j>=0;j--){ if(ch[j]==ch1[i]){ break; }} ch[j]=ch[i]; ch[i]=ch1[i];} String sne=toString(ch); if(sne.compareTo(st2)<0){ System.out.println(sne); } else{ System.out.println("---"); } } } } static String toString(char[] ch){ StringBuffer s=new StringBuffer(""); for(int i=0;i<ch.length;i++){ s.append(ch[i]); } return s.toString(); } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output
PASSED
f7dc0e2b7746473da231bdb3501f9ec2
train_000.jsonl
1576386300
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i &lt; b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j &lt; i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jaynil */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { StringBuilder x = new StringBuilder(in.next()); StringBuilder y = new StringBuilder(in.next()); boolean swapped = false; int b = 0; for (int i = 0; i < x.length(); i++) { Character bb = x.charAt(i); for (int j = i + 1; j < x.length(); j++) { if (x.charAt(j) <= bb) { b = j; bb = x.charAt(j); } } if (bb != x.charAt(i)) { x.setCharAt(b, x.charAt(i)); x.setCharAt(i, bb); break; } } if (x.compareTo(y) < 0) { out.println(x.toString()); } else out.println("---"); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"]
2 seconds
["AMAZON\n---\nAPPLE"]
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".
Java 11
standard input
[ "greedy" ]
88743b7acb4a95dc0d5bb2e073714c49
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.
1,600
For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible.
standard output