exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
ecb58fe7021bb27b48dbadaa764c976b
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main { public static void main(String[] args) throws IOException { //System.out.println("Hello World"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for(int p=0; p<t; p++){ String[] s = new String[3]; s = in.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); int k = Integer.parseInt(s[2]); int a1 = (int) Math.min(m, n/k); float x = (m-a1); int a2 = (int) Math.ceil(x/(k-1)); System.out.println(a1-a2); } } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
07c68607f466952e763fe04b2d1558c6
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.Scanner; public class Main { public static Scanner scanner=new Scanner(System.in); public static void main(String[] args) { int t=scanner.nextInt(); int n,m,k,d; while(t--!=0){ n=scanner.nextInt(); m=scanner.nextInt(); k=scanner.nextInt(); if(m<=(n/k)){ System.out.println(m); }else{ System.out.println((int)((n/k)-Math.ceil((float)(m-(n/k))/(k-1)))); } } } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
66e58f8981e8e02451e511b811abae12
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Minimise { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); StringBuilder res = new StringBuilder(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int a1 = Math.min(m, n / k); int a2 = (m - a1 + k - 2) / (k - 1); res.append(a1 - a2).append("\n"); } System.out.println(res); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
1b8606938ffd460da2d2c9226a4e4b2d
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class BerlandPoker { InputStream is; PrintWriter pw; String INPUT = ""; long L_INF = (1L << 60L); void solve() { int n=ni(), m=ni(),k=ni(); int card = n/k; if(card>=m) pw.println(m); else{ pw.println(card-((m-card+k-2)/(k-1))); } } void run() throws Exception { // is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); is = System.in; pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = ni(); while (t-- > 0) solve(); pw.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new BerlandPoker().run(); } private byte[] inbuf = new byte[1024]; private 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\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
b42b46b43a0e28d484b6bdf31a5fcec9
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String []args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int t=Integer.parseInt(br.readLine()); while(t-- >0){ String s[]=br.readLine().split(" "); int n=Integer.parseInt(s[0]); int m=Integer.parseInt(s[1]); int k=Integer.parseInt(s[2]); if(m==0 || (n==k && m!=1)){ bw.write("0\n"); continue; } else if(n/k>=m){ bw.write(m+"\n"); } else if(n/k<m){ int temp=n/k; bw.write(temp-(int)Math.ceil((double)(m-temp)/(k-1))+"\n"); } else{ bw.write("0\n"); } } bw.flush(); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
c5d7369cd4616280bbed1daf6064ef89
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
//package cp; import java.util.*; public class Cf { public static void main(String[] args) { int t; Scanner sc=new Scanner(System.in); t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); if(m/(n/k)==0) System.out.println(m); else if(k==2) { System.out.println((2*n/k)-m); } else if(m/(n/k)==k) System.out.println(0); else { int c=m-n/k; if(c%(k-1)==0) System.out.println(n/k-(c/(k-1))); else { System.out.println(n/k-(c/(k-1)+1)); } } } sc.close(); } } //4 //8 3 2 //4 2 4 //9 6 3 //42 0 7
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
7499b7740a332b327de5e56f3f1d3341
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static boolean[] sieve(int n){ boolean[] ret=new boolean[n+1]; Arrays.fill(ret,true); for(int i=0;i<=n;i++)ret[i]=true; for(int i=2;i*i<=n;i++){ if(ret[i]==false)continue; for(int j=i*i;j<=n;j+=i){ ret[j]=false; } } return ret; } static long calsum(long n){ return (n*(n+1))/2; } static long calsum(long x,long y){ y=x-y; y=(y*(y+1))/2; x=(x*(x+1))/2; return x-y; } static int bsrch(long[] sumdays,long x,int i){ int b=0,e=i,mid=0; while(b<=e){ mid=(b+e)/2; if(sumdays[i]-sumdays[mid+1]<=x && sumdays[i]-sumdays[mid]>x)return mid+1; else if(sumdays[i]-sumdays[mid]>x)b=mid+1; else e=mid-1; } return mid; } static boolean check(long[] a,long x,long k,long l){ long e=x; int n=a.length; for(int i=0;i<n;i++){ if(a[i]<e)e+=l; else if(a[i]==e)e-=k; else return false; } return true; } public static void main(String[] args)throws IOException{ FastReader in=new FastReader(); PrintWriter wr=new PrintWriter(System.out); int t=in.nextInt(); while(t-->0){ int n=in.nextInt(),m=in.nextInt(),k=in.nextInt(); int c=n/k; int rem=n-m; if(rem==0 || m==0){ wr.write("0\n"); wr.flush(); continue; } int maxj=c; if(m<=c){ wr.write(m+"\n"); wr.flush(); continue; } m-=c; if(m<k-1)m=1; else{ if(m%(k-1)==0)m=m/(k-1); else m=m/(k-1)+1; } if(c==m){ wr.write("0\n"); wr.flush(); } else{ wr.write(c-m+"\n"); wr.flush(); } } } } class FastReader{ public static StringTokenizer st; public static BufferedReader in; public static PrintWriter pw; FastReader(){ in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); st = new StringTokenizer(""); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static String next() throws IOException { while(!st.hasMoreElements() || st == null){ st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
fa117c953c6b4d655df99980d00936db
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.*; public class solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); if(m==0) { System.out.println(0); } else { int x=n/k; if(x>=m) { System.out.println(m); } else { int ans=(int) (x-Math.ceil((double)(m-x)/(double)(k-1))); System.out.println(ans); } } } sc.close(); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
5c103010e89cca689b84c72003d49049
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class codeforces4 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args){ FastReader f=new FastReader(); int t=f.nextInt(); while(t!=0){ t--; int n=f.nextInt(); int m=f.nextInt(); int k=f.nextInt(); double i=(double)(m-(n/k))/(k-1); if(i<=0)System.out.println(m); else if(i>0 &&i<n/k&&i==(int)i)System.out.println(n/k-(int)i); else if(i>0 &&i<n/k&&i!=(int)i)System.out.println(n/k-1-(int)i); else System.out.println(0); } } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
3f7e8d26cb95742ece7a33308fbcee00
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.nextLine(); for(int i = 0; i < n; i++) { int totalCards = scanner.nextInt(); int nJokers = scanner.nextInt(); int nPlayers = scanner.nextInt(); scanner.nextLine(); int cardsPrPlayer = totalCards/nPlayers; if(nJokers <= cardsPrPlayer) { System.out.println(nJokers); continue; } else { int jokersLeft = nJokers-cardsPrPlayer; int playersLeft = nPlayers-1; int result = 0; if(jokersLeft%playersLeft != 0) { result = jokersLeft/playersLeft +1; } else { result = jokersLeft/playersLeft; } System.out.println(cardsPrPlayer-result); } } } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
0ce9b7bec96720e19b56f5db9ba95827
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.*; import java.lang.String; import java.util.*; public class Main { private static int BinarySearch(int a[], int low, int high, int target) { if (low > high) return -1; int mid = low + (high - low) / 2; if (a[mid] == target) return mid; if (a[mid] > target) high = mid - 1; if (a[mid] < target) low = mid + 1; return BinarySearch(a, low, high, target); } static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static boolean[] sieve(int n) { boolean[] prime = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int i = 2; i * i <= n; i++) { if (prime[i] == true) { for (int p = i * i; p <= n; p += i) prime[p] = false; } } return prime; } static int max(int x, int y) { return (x > y) ? x : y; } static long smallestPrimeDivisor(long n) { if (n % 2 == 0) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n; } public static boolean IsPalindrome(String s, int n) { for (int i = 0; i < n / 2; i++) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } public static long[] shuffleArray(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } return arr; } public static long[] sorting(long[] arr) { shuffleArray(arr); Arrays.sort(arr); return arr; } public static boolean isPrime(int n) { if (n <= 1) return false; for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } static int modInverse(int a, int m) { a = a % m; for (int x = 1; x < m; x++) if ((a * x) % m == 1) return x; return 1; } public static void main(String[] args) { Scanner input = new Scanner(System.in); FastReader f = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int T = f.nextInt(); while (T-- > 0) { int n = f.nextInt(); int m = f.nextInt(); int k = f.nextInt(); int cards = n / k; if (m == 0) { pw.println(0); } else if (cards >= m) { pw.println(m); } else { m-=cards; int d = 0; int mod = m % (k-1); d=m/(k-1); if (mod>0) d++; pw.println(cards-d); } } pw.close(); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
a8b143dcf7b767daed2cc4741ae9f086
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.util.Scanner; public class BerlandPoker { public static void main(String[] args) { // read the input Scanner scanner = new Scanner(System.in); int t = Integer.parseInt(scanner.nextLine()); for(int i=0; i<t; i++){ String[] input = scanner.nextLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); int k = Integer.parseInt(input[2]); int cardsPerPlayer = n / k; int x, y; int remainingCards = 0; double jokerPerPlayer = 0; if (m ==0) System.out.println(0); // no joker, max score = 0 else if (m <= cardsPerPlayer) System.out.println(m); // give all joker cards to one player else if (m > cardsPerPlayer){ x = cardsPerPlayer; remainingCards = m - x; jokerPerPlayer = (double)remainingCards / (double)(k-1); y = (int)Math.ceil(jokerPerPlayer); System.out.println(x - y); } } scanner.close(); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output
PASSED
3fe7fa73c1de6111a7a627b653f70d31
train_003.jsonl
1503068700
Lech got into a tree consisting of n vertices with a root in vertex number 1. At each vertex i written integer ai. He will not get out until he answers q queries of the form u v. Answer for the query is maximal value among all vertices i on path from u to v including u and v, where dist(i, v) is number of edges on path from i to v. Also guaranteed that vertex u is ancestor of vertex v. Leha's tastes are very singular: he believes that vertex is ancestor of itself.Help Leha to get out.The expression means the bitwise exclusive OR to the numbers x and y.Note that vertex u is ancestor of vertex v if vertex u lies on the path from root to the vertex v.
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.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; 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); InATrap solver = new InATrap(); solver.solve(1, in, out); out.close(); } static class InATrap { int[] a; int[] stack; int[] depth; int sp; List<Integer>[] adj; int[] parent; int[] parent256; int[][] trie; int[] trieSumInSubtree; int numTrieNodes; int[][] bestHigh; int[][] bestLow; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int numQueries = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; adj[u].add(v); adj[v].add(u); } stack = new int[n]; depth = new int[n]; parent = new int[n]; parent256 = new int[n]; trie = new int[2][8 * n + 1]; trieSumInSubtree = new int[8 * n + 1]; numTrieNodes = 1; // root bestHigh = new int[n][256]; bestLow = new int[n][256]; for (int[] arr : trie) { Arrays.fill(arr, -1); } Arrays.fill(parent, -1); Arrays.fill(parent256, -1); dfs(0, -1); for (int i = 0; i < numQueries; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; int ans = 0; int block = 0; while (depth[v] - depth[u] >= 256) { int h = bestHigh[v][block]; ans = Math.max(ans, (h << 8) | bestLow[v][h ^ block]); ++block; v = parent256[v]; } int dist = 256 * block; while (v != parent[u]) { ans = Math.max(ans, a[v] ^ dist); ++dist; v = parent[v]; } out.println(ans); } } private void dfs(int v, int p) { if (sp >= 256) { parent256[v] = stack[sp - 256]; removeFromTrie(parent256[v]); } stack[sp++] = v; addToTrie(v); for (int u : adj[v]) { if (u == p) { continue; } parent[u] = v; depth[u] = 1 + depth[v]; dfs(u, v); } for (int i = 0; i < 256; i++) { bestHigh[v][i] = askTrie(i); } for (int i = 0; i < 256 && i <= depth[v]; i++) { int x = a[stack[sp - 1 - i]]; bestLow[v][x >> 8] = Math.max(bestLow[v][x >> 8], (x ^ i) & 255); } removeFromTrie(v); --sp; if (sp >= 256) { addToTrie(parent256[v]); } } private int askTrie(int x) { // max(x ^ label[c]) over all non-deleted // leaves c (those with positive sum in subtree). int res = 0; int c = 0; for (int i = 7; i >= 0; i--) { int bitX = (x >> i) & 1; if (trie[bitX ^ 1][c] >= 0 && trieSumInSubtree[trie[bitX ^ 1][c]] > 0) { res |= 1 << i; c = trie[bitX ^ 1][c]; } else { c = trie[bitX][c]; } } return res; } private void addToTrie(int v) { int x = a[v] >> 8; int c = 0; ++trieSumInSubtree[c]; for (int i = 7; i >= 0; i--) { int bit = (x >> i) & 1; if (trie[bit][c] < 0) { trie[bit][c] = numTrieNodes++; } c = trie[bit][c]; ++trieSumInSubtree[c]; } } private void removeFromTrie(int v) { int x = a[v] >> 8; int c = 0; --trieSumInSubtree[c]; for (int i = 7; i >= 0; i--) { int bit = (x >> i) & 1; c = trie[bit][c]; --trieSumInSubtree[c]; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3\n0 3 2 1 4\n1 2\n2 3\n3 4\n3 5\n1 4\n1 5\n2 4", "5 4\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5\n1 5\n2 5\n1 4\n3 3"]
3 seconds
["3\n4\n3", "5\n5\n4\n3"]
null
Java 8
standard input
[ "trees" ]
58310c2326a4c436df94a41c5c906eb6
First line of input data contains two integers n and q (1 ≤ n ≤ 5·104, 1 ≤ q ≤ 150 000) — number of vertices in the tree and number of queries respectively. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — numbers on vertices. Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n) — description of the edges in tree. Guaranteed that given graph is a tree. Each of next q lines contains two integers u and v (1 ≤ u, v ≤ n) — description of queries. Guaranteed that vertex u is ancestor of vertex v.
3,200
Output q lines — answers for a queries.
standard output
PASSED
9aac31a2fba720a0c4a9493f289be03d
train_003.jsonl
1503068700
Lech got into a tree consisting of n vertices with a root in vertex number 1. At each vertex i written integer ai. He will not get out until he answers q queries of the form u v. Answer for the query is maximal value among all vertices i on path from u to v including u and v, where dist(i, v) is number of edges on path from i to v. Also guaranteed that vertex u is ancestor of vertex v. Leha's tastes are very singular: he believes that vertex is ancestor of itself.Help Leha to get out.The expression means the bitwise exclusive OR to the numbers x and y.Note that vertex u is ancestor of vertex v if vertex u lies on the path from root to the vertex v.
256 megabytes
import java.io.*; import java.util.*; public class E { int[] a; static final int LOG = 8; static final int BLOCK = 1 << LOG; static final int LOW_MASK = BLOCK - 1; int[] head; int[] next; int[] to; int[] par; int[] depth; void dfs(int v, int p) { par[v] = p; for (int e = head[v]; e >= 0; e = next[e]) { int u = to[e]; if (u == p) { continue; } depth[u] = depth[v] + 1; dfs(u, v); } } int[][] go = new int[2][BLOCK * LOG + 1]; int triePtr = 0; int newNode() { go[0][triePtr] = go[1][triePtr] = -1; return triePtr++; } void submit() { int n = nextInt(); int q = nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } head = new int[n]; next = new int[2 * n - 2]; to = new int[2 * n - 2]; Arrays.fill(head, -1); for (int i = 0; i < n - 1; i++) { int v = nextInt() - 1; int u = nextInt() - 1; to[2 * i] = u; next[2 * i] = head[v]; head[v] = 2 * i; to[2 * i + 1] = v; next[2 * i + 1] = head[u]; head[u] = 2 * i + 1; } par = new int[n]; depth = new int[n]; dfs(0, -1); int[] parBlock = new int[n]; int[][] prec = new int[n][]; for (int i = 0; i < n; i++) { if (depth[i] < BLOCK) { continue; } int[] bestLow = new int[BLOCK]; Arrays.fill(bestLow, -1); int v = i; for (int j = 0; j < BLOCK; j++) { int now = a[v] ^ j; int low = now & LOW_MASK; int high = now >> LOG; bestLow[high] = Math.max(bestLow[high], low); v = par[v]; } parBlock[i] = v; triePtr = 0; int root = newNode(); for (int j = 0; j < BLOCK; j++) { if (bestLow[j] == -1) { continue; } v = root; for (int k = LOG - 1; k >= 0; k--) { int bit = getBit(j, k); if (go[bit][v] == -1) { go[bit][v] = newNode(); } v = go[bit][v]; } } prec[i] = new int[BLOCK]; for (int j = 0; j < BLOCK; j++) { v = root; int highPicked = 0; for (int k = LOG - 1; k >= 0; k--) { int bit = getBit(j, k); if (go[bit ^ 1][v] != -1) { highPicked |= (bit ^ 1) << k; v = go[bit ^ 1][v]; } else { highPicked |= bit << k; v = go[bit][v]; } } prec[i][j] = ((highPicked ^ j) << LOG) | bestLow[highPicked]; } } while (q-- > 0) { int top = nextInt() - 1; int btm = nextInt() - 1; int ret = 0; int i = 0; for (;; i++) { if (depth[btm] - BLOCK >= depth[top]) { ret = Math.max(ret, prec[btm][i]); btm = parBlock[btm]; } else { break; } } i <<= LOG; while (btm != -1 && depth[btm] >= depth[top]) { ret = Math.max(ret, a[btm] ^ i); btm = par[btm]; i++; } out.println(ret); } } int getBit(int mask, int i) { return (mask >> i) & 1; } void preCalc() { } void stress() { } void test() { } E() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); preCalc(); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new E(); } BufferedReader br; PrintWriter out; StringTokenizer st; String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["5 3\n0 3 2 1 4\n1 2\n2 3\n3 4\n3 5\n1 4\n1 5\n2 4", "5 4\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5\n1 5\n2 5\n1 4\n3 3"]
3 seconds
["3\n4\n3", "5\n5\n4\n3"]
null
Java 8
standard input
[ "trees" ]
58310c2326a4c436df94a41c5c906eb6
First line of input data contains two integers n and q (1 ≤ n ≤ 5·104, 1 ≤ q ≤ 150 000) — number of vertices in the tree and number of queries respectively. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — numbers on vertices. Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n) — description of the edges in tree. Guaranteed that given graph is a tree. Each of next q lines contains two integers u and v (1 ≤ u, v ≤ n) — description of queries. Guaranteed that vertex u is ancestor of vertex v.
3,200
Output q lines — answers for a queries.
standard output
PASSED
9b29a828970fe5bf3fa3a15f6b901469
train_003.jsonl
1503068700
Lech got into a tree consisting of n vertices with a root in vertex number 1. At each vertex i written integer ai. He will not get out until he answers q queries of the form u v. Answer for the query is maximal value among all vertices i on path from u to v including u and v, where dist(i, v) is number of edges on path from i to v. Also guaranteed that vertex u is ancestor of vertex v. Leha's tastes are very singular: he believes that vertex is ancestor of itself.Help Leha to get out.The expression means the bitwise exclusive OR to the numbers x and y.Note that vertex u is ancestor of vertex v if vertex u lies on the path from root to the vertex v.
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.Arrays; import java.util.StringTokenizer; public class Div1_429E { static int nV; static int[] vals = new int[50_000]; static int[] block = new int[50_000]; static int[] p256 = new int[50_000]; static int[] cnt = new int[256 * 8 * 2]; static int[][] maxLower = new int[50_000][256]; static int[][] maxUpper = new int[50_000][256]; static int[] ePt = new int[100_000]; static int[] nxt = new int[100_000]; static int[] lSt = new int[50_000]; static int[] par = new int[50_000]; static int[] ht = new int[50_000]; static int[] stack = new int[50_000]; static int sI; public static void main0(String[] args) throws IOException { mTrie(0b0100001, 1); System.out.println(Integer.toBinaryString(qTrie(0b100000))); mTrie(0b100000, 1); System.out.println(Integer.toBinaryString(qTrie(0b100000))); mTrie(0b100000, -1); System.out.println(Integer.toBinaryString(qTrie(0b100000))); } public static void main(String[] args) throws IOException { Arrays.fill(block, -1); Arrays.fill(p256, -1); Arrays.fill(lSt, -1); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer inputData = new StringTokenizer(reader.readLine()); nV = Integer.parseInt(inputData.nextToken()); int nQ = Integer.parseInt(inputData.nextToken()); inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nV; i++) { vals[i] = Integer.parseInt(inputData.nextToken()); } int nE = 0; for (int i = 0; i < nV - 1; i++) { inputData = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(inputData.nextToken()) - 1; int b = Integer.parseInt(inputData.nextToken()) - 1; ePt[nE] = b; nxt[nE] = lSt[a]; lSt[a] = nE++; ePt[nE] = a; nxt[nE] = lSt[b]; lSt[b] = nE++; } prep(0, -1); while (nQ-- > 0) { inputData = new StringTokenizer(reader.readLine()); int e = Integer.parseInt(inputData.nextToken()) - 1; int s = Integer.parseInt(inputData.nextToken()) - 1; printer.println(query(s, e)); } printer.close(); } static int query(int cV, int eV) { int max = 0; int cDist = 0; int cP256 = p256[cV]; while (cP256 != -1 && ht[cP256] >= ht[eV]) { int cMaxUpper = maxUpper[cV][cDist >> 8]; int cMaxLower = maxLower[cV][cMaxUpper ^ (cDist >> 8)]; int cur = (cMaxUpper << 8) + cMaxLower; max = Math.max(max, cur); cV = cP256; cP256 = p256[cV]; cDist += 256; } while (cV != -1 && cV != eV) { int cXor = vals[cV] ^ cDist; if (cXor > max) { max = cXor; } cDist++; cV = par[cV]; } if (cV == eV) { max = Math.max(max, vals[cV] ^ cDist); } return max; } static void prep(int cV, int pV) { par[cV] = pV; stack[sI++] = cV; for (int cI = 1; cI <= 256 && cI <= sI; cI++) { int cVal = vals[stack[sI - cI]]; maxLower[cV][cVal >> 8] = Math.max(maxLower[cV][cVal >> 8], (cVal & 255) ^ (cI - 1)); } mTrie(vals[cV] >> 8, 1); if (sI > 256) { p256[cV] = stack[sI - 257]; mTrie(vals[stack[sI - 257]] >> 8, -1); } for (int i = 0; i < 256; i++) { maxUpper[cV][i] = qTrie(i); } int cHt = ht[cV]; int eI = lSt[cV]; while (eI != -1) { int aV = ePt[eI]; if (aV != pV) { ht[aV] = cHt + 1; prep(aV, cV); } eI = nxt[eI]; } mTrie(vals[cV] >> 8, -1); if (sI > 256) { mTrie(vals[stack[sI - 257]] >> 8, 1); } sI--; } static int qTrie(int query) { int cNode = 1; int ans = 0; for (int i = 7; i >= 0; i--) { int cB = (query >> i) & 1; if (cnt[2 * cNode + (cB ^ 1)] > 0) { ans |= (1 << i); cNode = 2 * cNode + (cB ^ 1); } else { cNode = 2 * cNode + cB; } } return ans; } static void mTrie(int ind, int dlt) { int cNode = 1; for (int i = 7; i >= 0; i--) { cnt[cNode] += dlt; cNode = 2 * cNode + ((ind >> i) & 1); } cnt[cNode] += dlt; } }
Java
["5 3\n0 3 2 1 4\n1 2\n2 3\n3 4\n3 5\n1 4\n1 5\n2 4", "5 4\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5\n1 5\n2 5\n1 4\n3 3"]
3 seconds
["3\n4\n3", "5\n5\n4\n3"]
null
Java 8
standard input
[ "trees" ]
58310c2326a4c436df94a41c5c906eb6
First line of input data contains two integers n and q (1 ≤ n ≤ 5·104, 1 ≤ q ≤ 150 000) — number of vertices in the tree and number of queries respectively. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — numbers on vertices. Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n) — description of the edges in tree. Guaranteed that given graph is a tree. Each of next q lines contains two integers u and v (1 ≤ u, v ≤ n) — description of queries. Guaranteed that vertex u is ancestor of vertex v.
3,200
Output q lines — answers for a queries.
standard output
PASSED
2fad8f597b823474dbd3b37d20c7c7b6
train_003.jsonl
1588775700
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class S { public static void main (String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t--!=0) { int n=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=in.nextInt(); Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { long z=i+a[i]; z=((z%n)+n)%n; if(!map.containsKey(z))map.put(z,1L); else map.put(z,map.get(z)+1); } int temp=0; Set<Map.Entry<Long,Long>> set=map.entrySet(); for(Map.Entry<Long,Long> m:set) { if(m.getValue()>1) { temp=1; break; } } if(temp==1)System.out.println("NO"); else System.out.println("YES"); } } }
Java
["6\n1\n14\n2\n1 -1\n4\n5 5 5 1\n3\n3 2 1\n2\n0 1\n5\n-239 -2 -100 -3 -11"]
1 second
["YES\nYES\nYES\nNO\nNO\nYES"]
NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$.
Java 8
standard input
[ "sortings", "math" ]
2173310623173d761b6039f0e5e661a8
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.
1,600
For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
b293392400f7532b8fd87a49ff667c00
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class PalindromeDegree { static final long B = 33; static final long C = 127; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); char[] s = in.readLine().toCharArray(); int n = s.length, i; long h1, h1r, h2, h2r, sum, p1, p2; long[] degree = new long[n]; h1 = h1r = h2 = h2r = s[0] - 'a' + 1; sum = 1; degree[0] = 1; p1 = p2 = 1; for (i = 1; i < n; ++i) { p1 = p1*B; p2 = p2*C; long c = s[i] - 'a' + 1; h1 = h1 + c*p1; h1r = h1r*B + c; h2 = h2 + c*p2; h2r = h2r*C + c; if (h1 == h1r && h2 == h2r) degree[i] = degree[(i-1)/2]+1; else degree[i] = 0; sum = sum + degree[i]; } System.out.println(sum); } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
49693f9c477d0723c68900932edb36ed
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * CodeForces Round 7D - Palindrome Degree * Created by Darren on 14-9-26. */ public class Main { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new Main().run(); } void run() throws IOException { char[] str = in.readLine().toCharArray(); int n = str.length; int[] dp = new int[n+1]; dp[0] = 0; int sum = 0; int forward = 0, backward = 0, power = 1; for (int i = 0; i < n; i++, power *= 31) { forward = forward * 31 + str[i]; backward += str[i] * power; if (forward == backward) { dp[i+1] = dp[(i+1)>>1] + 1; sum += dp[i+1]; } } out.println(sum); out.flush(); } static class Reader { BufferedReader reader; StringTokenizer tokenizer; public Reader(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ String nextToken() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } String readLine() throws IOException { return reader.readLine(); } int nextInt() throws IOException { return Integer.parseInt( nextToken() ); } long nextLong() throws IOException { return Long.parseLong( nextToken() ); } double nextDouble() throws IOException { return Double.parseDouble( nextToken() ); } } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
93c5323242823a53f2382cea2580cb37
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
//package hw5; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ZAlgo { public static void main(String[] args) throws IOException { BufferedReader readInput = new BufferedReader(new InputStreamReader(System.in)); String str = readInput.readLine(); int n = str.length(); StringBuffer newStr = new StringBuffer(); newStr.append(str); for(int i = n-1; i >= 0; i--) { newStr.append(str.charAt(i)); } int[] zVals = zValues(newStr.toString()); int solution = solve(zVals, n); System.out.println(solution); } public static int solve(int[] zVals, int n) { int[] degrees = new int[n+1]; int degree = 0; for (int i = 1; i <= n; i++) { if (zVals[n+n-i] == i) { int d = degrees[i/2] + 1; degrees[i] = d; degree += d; } } return degree; } // http://codeforces.com/blog/entry/3107 static int[] zValues(String str) { int L = 0; int R = 0; int n = str.length(); int[] z = new int[n]; char[] s = str.toCharArray(); for(int i = 1; i < n; i++) { if(i > R) { L = i; 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--; } } } return z; } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
34f1ad3c77c32a2b53d890f5a3116fb5
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Palindrome { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); char[] cstr=in.readLine().toCharArray(); int size=cstr.length; char[] cstr2=new char[size*2]; for (int i=0;i<size;++i){ cstr2[i]=cstr[i]; cstr2[size*2-i-1]=cstr[i]; } int[] z=getz(cstr2); int[] pal=new int[size]; pal[0]=1; int sum=1; for (int i=1;i<size;++i){ int j=size*2-i-1; if(z[j]==i+1) pal[i]=pal[(i-1)/2]+1; else pal[i]=0; sum+=pal[i]; } out.write(""+sum); out.close(); } private static int[] getz(char[] cstr) { int size=cstr.length; int[] z=new int[size]; z[0]=size; int l=0,r=0; for (int i = 1; i < size; ++i) { if (i > r) { l = r = i; while (r < size && cstr[r-l] == cstr[r])++r; z[i] = r-l; --r; }else { if (z[i-l] <= r-i) z[i] = z[i-l]; else { l = i; while (r < size && cstr[r-l] == cstr[r])++r; z[i] = r-l; --r; } } } return z; } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
60184205e3740bd9ee701ce3a4cee41c
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
import java.io.*; import java.util.*; public class CF { // long mod = (long) 1e9 + 7; int[] pow; long mul = 53; int[] getHash(String s) { int n = s.length(); int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = (int) ((s.charAt(i) + (i == 0 ? 0 : mul * res[i - 1]))); } return res; } int[] h1, h2; boolean isPalindrome(int len) { if (len == 1) return true; int n = h1.length; int hh1 = h1[len / 2 - 1]; int fr = n - len - 1; int to = fr + len / 2; int sz = to - fr; int hh2 = (int) (h2[to] - (fr < 0 ? 0 : h2[fr]) * 1L * pow[sz]); // hh2 = ((hh2 % mod) + mod) % mod; return hh1 == hh2; } int[] getPowers(int n) { int[] res = new int[n + 1]; res[0] = 1; for (int i = 1; i <= n; i++) { res[i] = (int) ((res[i - 1] * mul)); } return res; } void realSolve() { String s = in.next(); String sRev = new StringBuilder(s).reverse().toString(); h1 = getHash(s); h2 = getHash(sRev); pow = getPowers(s.length() + 1); int[] res = new int[s.length()]; long ans = 0; for (int i = 0; i < s.length(); i++) { if (isPalindrome(i + 1)) { res[i] = 1 + (i == 0 ? 0 : res[(i - 1) / 2]); } ans += res[i]; } out.println(ans); } private class InputReader { StringTokenizer st; BufferedReader br; 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)); } String next() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return null; } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } boolean hasMoreElements() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return false; } st = new StringTokenizer(s); } return st.hasMoreElements(); } long nextLong() { return Long.parseLong(next()); } } InputReader in; PrintWriter out; void solve() { in = new InputReader(new File("object.in")); try { out = new PrintWriter(new File("object.out")); } catch (FileNotFoundException e) { e.printStackTrace(); } realSolve(); out.close(); } void solveIO() { in = new InputReader(System.in); out = new PrintWriter(System.out); realSolve(); out.close(); } public static void main(String[] args) { new CF().solveIO(); } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
8616d2ab71928a2870f31c0354014d85
train_003.jsonl
1270136700
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class cf7d { public static void main(String[] args) { FastIO in = new FastIO(), out = in; long p1 = 18409199; long p2 = 18409199+2; long p1cur = 1, p2cur = 1; char[] v = in.next().trim().toCharArray(); long[] ans = new long[v.length+1]; long ret = 0; long h11 = 0, h12 = 0, h21 = 0, h22 = 0; for(int i=1; i<=v.length; i++) { char c = v[i-1]; h11 = h11*p1 + c; h12 = h12 + c*p1cur; h21 = h21*p2 + c; h22 = h22 + c*p2cur; p1cur *= p1; p2cur *= p2; if(h11 == h12 && h21 == h22) { ret += ans[i] = ans[i/2]+1; } } out.println(ret); out.close(); } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in,System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if(!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if(!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["a2A", "abacaba"]
1 second
["1", "6"]
null
Java 7
standard input
[ "hashing", "strings" ]
0090979443c294ef6aed7cd09201c9ef
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
2,200
Output the only number — the sum of the polindrome degrees of all the string's prefixes.
standard output
PASSED
93915723c81f8388cfdcda7fc68b71b2
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MaxSeq { public static void main( final String[] args ) throws IOException { final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); final String s = br.readLine(); System.out.println( solve( s ) ); } private static String solve( final String s ) { if ( s.length() == 0 ) return ""; final char[] ca = s.toCharArray(); char max = ca[ 0 ]; for ( int i = 1; i < ca.length; ++i ) { if ( ca[ i ] > max ) max = ca[ i ]; } final StringBuilder buff = new StringBuilder(); int li = 0; for ( int i = 0; i < ca.length; ++i ) { if ( ca[ i ] == max ) { buff.append( max ); li = i; } } return buff.append( solve( s.substring( li + 1 ) ) ).toString(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
954902070e8dbee533771f9d3a8eb9d5
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class two { public static void main(String[] args) throws IOException { BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); char[] c = buf.readLine().toCharArray(); StringBuilder ans = new StringBuilder(""); String s = "abcdefghijklmnopqrstuvwxyz"; char[] alp = s.toCharArray(); int last = 0; for (int i = 25; i >= 0; i--) { for (int j = last; j < c.length; j++) { if (c[j] == alp[i]) { ans.append(c[j] + ""); last = j; } } } System.out.println(ans); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
a740f3ac984d9e65b7ad693c681459f9
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CF124C { public static void main(String[] args) throws IOException { char[] s = new BufferedReader(new InputStreamReader(System.in)) .readLine().trim().toCharArray(); StringBuilder ans = new StringBuilder(s[s.length - 1] + ""); for (int i = s.length - 2; i >= 0; i--) { int last = ans.length() - 1; if (s[i] >= ans.charAt(last)) ans = ans.append(s[i]); } System.out.println(ans.reverse().toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
a4f4367b5f75d17ace4b4f8a3e296dae
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class Main { BufferedReader br; int n, m; char c; String s; StringBuilder sb; public void go() throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine(); sb = new StringBuilder(); c = '0'; for (int i = s.length() - 1; i >= 0; i--) if (s.charAt(i) >= c) { sb.append(s.charAt(i)); c = s.charAt(i); } System.out.println(sb.reverse().toString()); } public static void main(String[] args) throws Exception { new Main().go(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
9b98c50110234798c730a1c0448c9ba0
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.util.Scanner; public class C197 { public static void main(String[] args) throws IOException { solve(); } public static void solve()throws IOException{ Scanner scan = new Scanner(new BufferedInputStream(System.in)); char sq[] = scan.next().toCharArray(); char toFind = 'z'; StringBuilder ans = new StringBuilder(); int lastFound = 0; while(toFind >= 'a') { int i = lastFound; for (; i < sq.length; i++) { if(sq[i] == toFind){ ans.append(toFind); lastFound = i; } } toFind--; } System.out.println(ans.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b2ff34e059dcaa6f2e3a95afdc4802c0
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.text.*; import java.io.BufferedReader;import java.math.*; import java.util.regex.*; import java.awt.geom.*; import static java.lang.Math.*; import static java.lang.Character.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; import static java.lang.System.*; import static java.util.Arrays.*; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; public class C { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static PrintStream out = System.out; static int m = 0, n = 0; static int result = 0; static String s = ""; static int[] last; static void readInput() throws IOException { s = in.readLine(); last = new int[1000]; } static void process() { fill(last, -1); char[] c = s.toCharArray(); for (int i = 0; i < s.length(); i++) { last[c[i]] = i; } int u = -1; StringBuffer sb = new StringBuffer(); do { // debug(u); char k=' '; for(char cc='z'; cc>='a'; cc--) { if (last[cc] >u ) { k = cc; break; } } if (k==' ') break; for (int i = u+1; i <= last[k]; i++) { if (c[i]==k) sb.append(k); } u=last[k]; } while (true); out.println(sb.toString()); } public static void main(String[] args) throws IOException { readInput(); process(); } public static void debug(Object...os) { System.err.println(Arrays.deepToString(os)); } static int[] readArrInt() throws IOException { return parseArrInt(in.readLine()); } static int readInt() throws IOException { return new Integer(in.readLine()); } static int[] parseArrInt(String s) { StringTokenizer st = new StringTokenizer(s); ArrayList<Integer> list = new ArrayList<Integer>(); while (st.hasMoreTokens()) { list.add(Integer.parseInt(st.nextToken())); } Integer[] temp = list.toArray(new Integer[]{}); int[] res = new int[temp.length]; for (int i = 0; i < temp.length; i++) { res[i] = temp[i]; } return (res); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
6a2d1bcbd76766f70f1b554df135d3ec
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; import java.io.PrintStream; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author @zhendeaini6001 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { String s = in.next(); int[] begin = new int[26]; int[] end = new int[26]; StringBuilder sb = new StringBuilder(); Arrays.fill(begin, -1); Arrays.fill(end, -1); for (int i = 0; i < s.length(); ++i){ int index = s.charAt(i) - 'a'; if (begin[index] == -1){ begin[index] = i; end[index] = i; } else{ end[index] = i; } } int cur = -1; for (int i = 25; i >= 0; --i){ if (begin[i] == -1 || cur == s.length() - 1){ continue; } if (end[i] < cur){ continue; } for (int j = Math.max(begin[i], cur); j <= end[i]; ++j){ if (s.charAt(j) == 'a' + i){ sb.append(s.charAt(j)); } } cur = end[i]; } out.println(sb.toString()); return; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
1746cbe4cdaa92d43f91cc2f691968e9
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author andrey */ public class CC { public static void main(String aewgd[])throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); char[] a = in.readLine().toCharArray(); int b[] = new int[a.length]; char max = 'a'-1; int prev = -1; for(int i=a.length-1;i>=0;i--) if(a[i]>=max){ b[i] = prev; prev = i; max = a[i]; } while(prev!=-1){ System.out.print(a[prev]); prev = b[prev]; } System.out.println(); in.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
6eb14ac09f1604da9e4cac780e7e0836
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class MaximalSubsequence { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String input = in.next(); int[] maxCharIndex = new int[input.length()]; maxCharIndex[maxCharIndex.length - 1] = maxCharIndex.length - 1; char[] maxChars = new char[input.length()]; maxChars[maxChars.length - 1] = input.charAt(maxChars.length - 1); for (int i = maxCharIndex.length - 2; i > -1; i--) { char toTest = input.charAt(i); if (toTest < maxChars[ maxCharIndex[i + 1] ]) { maxCharIndex[i] = maxCharIndex[i + 1]; maxChars[i] = maxChars[i + 1]; } else { maxCharIndex[i] = i; maxChars[i] = toTest; } } StringBuilder maximalSubstring = new StringBuilder(input.length()); for (int i = 0; i < input.length(); i = maxCharIndex[i] + 1) { maximalSubstring.append( input.charAt( maxCharIndex[i] ) ); } PrintWriter out = new PrintWriter(System.out); out.println(maximalSubstring); out.flush(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
d30dfaf7b5e1686fd9126ca7b6ae0f8d
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; public class C124 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CodeC124 solver = new CodeC124(); solver.solve(1, in, out); out.close(); } } class CodeC124 { public void solve(int testNumber, InputReader in, PrintWriter out) { String s=in.next(); int l=s.length(); char[][] arr=new char[l][2]; for(int i=0;i<l;i++) { arr[i][0]=s.charAt(i); arr[i][1]='a'; } char max='a'; for(int i=l-1;i>=0;i--) { if(arr[i][0]>max) { arr[i][1]=arr[i][0]; max=arr[i][0]; } else { arr[i][1]=max; } } for(int i=0;i<l;i++) { if(arr[i][1]==arr[i][0]) { out.print(arr[i][0]); } } } } class InputReader { private BufferedReader reader; private 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 int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void inputShuffleArrayInt(int arr[]) { int l=arr.length; for(int i=0;i<l;i++) { if(i%2==0) { arr[i/2]=nextInt(); } else { arr[l-((i+1)/2)]=nextInt(); } } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ddc4b8d44746514d1ee4acd9ec24379e
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import static java.lang.Math.*; import java.util.*; import java.io.*; public class C { public void solve() throws Exception { char[] s = nextLine().toCharArray(); LinkedList<Integer>[] ll = new LinkedList[30]; for (int i=0; i<30; ++i) ll[i] = new LinkedList<Integer>(); for (int i=0; i<s.length; ++i) ll[s[i]-'a'].add(i); // debug(ll); int pos = -1; for (int i=29; i>=0; --i) { if (ll[i].size()!=0) { for (int x: ll[i]) { if (x>pos) { pos=x; print((char)(i+'a')); } } } } println(); } //////////////////////////////////////////////////////////////////////////// boolean showDebug = true; static boolean useFiles = false; static String inFile = "input.txt"; static String outFile = "output.txt"; double EPS = 1e-7; int INF = Integer.MAX_VALUE; long INFL = Long.MAX_VALUE; double INFD = Double.MAX_VALUE; int absPos(int num) { return num<0 ? 0:num; } long absPos(long num) { return num<0 ? 0:num; } double absPos(double num) { return num<0 ? 0:num; } int min(int... nums) { int r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]<r) r=nums[i]; return r; } int max(int... nums) { int r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]>r) r=nums[i]; return r; } long minL(long... nums) { long r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]<r) r=nums[i]; return r; } long maxL(long... nums) { long r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]>r) r=nums[i]; return r; } double minD(double... nums) { double r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]<r) r=nums[i]; return r; } double maxD(double... nums) { double r = nums[0]; for (int i=1; i<nums.length; ++i) if (nums[i]>r) r=nums[i]; return r; } long sumArr(int[] arr) { long res = 0; for (int i=0; i<arr.length; ++i) res+=arr[i]; return res; } long sumArr(long[] arr) { long res = 0; for (int i=0; i<arr.length; ++i) res+=arr[i]; return res; } double sumArr(double[] arr) { double res = 0; for (int i=0; i<arr.length; ++i) res+=arr[i]; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<<pos))>0; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } boolean charIn(String chars, String s) { if (s==null) return false; if (chars==null || chars.equals("")) return true; for (int i=0; i<s.length(); ++i) for (int j=0; j<chars.length(); ++j) if (chars.charAt(j)==s.charAt(i)) return true; return false; } String stringn(String s, int n) { if (n<1 || s==null) return ""; StringBuilder sb = new StringBuilder(s.length()*n); for (int i=0; i<n; ++i) sb.append(s); return sb.toString(); } String str(Object o) { if (o==null) return ""; return o.toString(); } long timer = System.currentTimeMillis(); void startTimer() { timer = System.currentTimeMillis(); } void stopTimer() { System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0); } static class InputReader { private byte[] buf; private int bufPos = 0, bufLim = -1; private InputStream stream; public InputReader(InputStream stream, int size) { buf = new byte[size]; this.stream = stream; } private void fillBuf() throws IOException { bufLim = stream.read(buf); bufPos = 0; } char read() throws IOException { if (bufPos>=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos<bufLim; } } static InputReader inputReader; static BufferedWriter outputWriter; char nextChar() throws IOException { return inputReader.read(); } char nextNonWhitespaceChar() throws IOException { char c = inputReader.read(); while (c<=' ') c=inputReader.read(); return c; } String nextWord() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c>' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i<size; ++i) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i=0; i<size; ++i) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i=0; i<size; ++i) arr[i] = nextDouble(); return arr; } String[] nextArrS(int size) throws NumberFormatException, IOException { String[] arr = new String[size]; for (int i=0; i<size; ++i) arr[i] = nextWord(); return arr; } char[] nextArrCh(int size) throws IOException { char[] arr = new char[size]; for (int i=0; i<size; ++i) arr[i] = nextNonWhitespaceChar(); return arr; } char[][] nextArrCh(int rows, int columns) throws IOException { char[][] arr = new char[rows][columns]; for (int i=0; i<rows; ++i) for (int j=0; j<columns; ++j) arr[i][j] = nextNonWhitespaceChar(); return arr; } char[][] nextArrChBorders(int rows, int columns, char border) throws IOException { char[][] arr = new char[rows+2][columns+2]; for (int i=1; i<=rows; ++i) for (int j=1; j<=columns; ++j) arr[i][j] = nextNonWhitespaceChar(); for (int i=0; i<columns+2; ++i) { arr[0][i] = border; arr[rows+1][i] = border; } for (int i=0; i<rows+2; ++i) { arr[i][0] = border; arr[i][columns+1] = border; } return arr; } void printf(String format, Object... args) throws IOException { outputWriter.write(String.format(format, args)); } void print(Object o) throws IOException { outputWriter.write(o.toString()); } void println(Object o) throws IOException { outputWriter.write(o.toString()); outputWriter.newLine(); } void print(Object... o) throws IOException { for (int i=0; i<o.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(o[i].toString()); } } void println(Object... o) throws IOException { print(o); outputWriter.newLine(); } void printn(Object o, int n) throws IOException { String s = o.toString(); for (int i=0; i<n; ++i) { outputWriter.write(s); if (i!=n-1) outputWriter.write(' '); } } void printnln(Object o, int n) throws IOException { printn(o, n); outputWriter.newLine(); } void printArr(int[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Integer.toString(arr[i])); } } void printArr(long[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Long.toString(arr[i])); } } void printArr(double[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Double.toString(arr[i])); } } void printArr(String[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(arr[i]); } } void printlnArr(int[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(long[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(double[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(String[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void halt(Object... o) throws IOException { if (o.length!=0) println(o); outputWriter.flush(); outputWriter.close(); System.exit(0); } void debug(Object... o) { if (showDebug) System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); if (!useFiles) { inputReader = new InputReader(System.in, 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16); } else { inputReader = new InputReader(new FileInputStream(new File(inFile)), 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outFile))), 1<<16); } new C().solve(); outputWriter.flush(); outputWriter.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
46b6d4ae75263203b96fa8ae44692e04
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; /** * */ public class Solution { /** * @param args */ public static void main(String[] args){ try { BufferedReader reader =new BufferedReader(new InputStreamReader(System.in)); // STDIN String str=reader.readLine().trim(); String subsequence=""; String alphabet="abcdefghijklmnopqrstuvwxyz"; for(int i=alphabet.length()-1;i>=1;i--){ char ch=alphabet.charAt(i); String pattern=alphabet.substring(0,i); int last=str.lastIndexOf(ch); if(last>0){ String sub=str.substring(0, last); subsequence+=sub.replaceAll("["+pattern+"]", ""); str=str.substring(last); }} subsequence+=str; System.out.println(subsequence); }catch(Exception e){ e.printStackTrace(System.err); }}}
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
66718ef612e67ca52ac6f32196fbe5e7
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); ArrayList<Integer> ar = new ArrayList<Integer>(); char max = 'a'; for (int i = s.length() - 1; i >= 0; --i) if (s.charAt(i) >= max) { ar.add(i); max = s.charAt(i); } Collections.reverse(ar); for (int i : ar) System.out.print(s.charAt(i)); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e5d12294f9ab8dcc8b3df828c5d5b364
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); String s=c.nextLine(); char A[]=(""+((char)('a'-1))+s).toCharArray(); int N=A.length; int maxLoc[]=new int[N]; maxLoc[N-1]=-1; if(N==1) { System.out.println(s); return; } maxLoc[N-2]=N-1; int curPos=N-1; for(int i=N-3;i>=0;i--) { if(A[i+1]>=A[curPos]) { maxLoc[i]=i+1; curPos=i+1; } else maxLoc[i]=curPos; } //System.out.println(Arrays.toString(maxLoc)); StringBuffer ans=new StringBuffer(""); int loc=0; while(loc<N&&loc!=-1) { loc=maxLoc[loc]; if(loc!=-1) ans=ans.append(A[loc]); } System.out.println(ans); } } //must declare new classes here
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ca2c39cf985137fdfa05231faedd3bad
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; public class C { public String solve( String sample){ StringBuffer res = new StringBuffer(); char [] cs = sample.toCharArray(); char last = 0; int lastIdx = 0; char min = cs[0]; for( int i=0;i<cs.length;i++){ if( min > cs[i]) min = cs[i]; } while( true) { char now = 0; for( int j=0;j<cs.length;j++){ if( (last == 0 || ( last > 0 && cs[j] < last )) && cs[j] > now) { now = cs[j]; } } if( now != 0 ) { for( int j = lastIdx ; j < cs.length ; j ++) { if( cs[j] == now) { res.append(now); lastIdx = j; } } last = now ; } if( lastIdx + 1 == cs.length || last == min) { break; } } return res.toString(); } public static void main (String [] args) { C solution = new C(); Scanner cin = new Scanner(System.in); while ( cin.hasNext()) { String str = cin.next(); System.out.println(solution.solve(str)); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
0581dff244f272e9303cad35cff668e4
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
//package contest_124_div2; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StreamTokenizer; import java.io.Writer; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; /** * Date : 12 ����. 2012 * Time : 15:33:28 * Email : denys.astanin@gmail.com */ public class C { public static void main(String[] args) throws IOException { new C().run(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String nextString() throws IOException { in.nextToken(); return (String) in.sval; } StreamTokenizer in; Writer writer; Reader reader; public static class MyChar implements Comparable<MyChar> { char ch; public MyChar(char ch) { this.ch = ch; } @Override public int compareTo(MyChar arg0) { return -(ch - arg0.ch); } } void run() throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader("src/contest_124_div2/C.txt"); writer = new OutputStreamWriter(System.out, "ISO-8859-1"); in = new StreamTokenizer(new BufferedReader(reader)); PrintWriter out = new PrintWriter(writer); Map<Character, MyChar> cache = new HashMap<Character, MyChar>(); String s = nextString(); Map<MyChar, Integer> start = new HashMap<MyChar, Integer>(); Map<MyChar, Integer> end = new HashMap<MyChar, Integer>(); Queue<MyChar> queue = new PriorityQueue<MyChar>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); MyChar mch = cache.get(ch); if (mch == null) { mch = new MyChar(ch); cache.put(ch, mch); queue.add(mch); } if (start.get(mch) == null) { start.put(mch, i); } end.put(mch, i); } StringBuilder b = new StringBuilder(); MyChar current = queue.poll(); for (int i = start.get(current); i < s.length(); i++) { while (i > end.get(current)) { current = queue.poll(); } char ch = s.charAt(i); MyChar mch = cache.get(ch); if (mch.ch == current.ch) { b.append(ch); } } // int[] arr = new int[s.length()]; // for (int i = 0; i < arr.length; i++) { // arr[i] = s.charAt(i); // } // int[] lis = getLIS(arr); // for (Integer i : lis) { // out.print(Character.toChars(i)); // } out.println(b.toString()); out.flush(); out.close(); } int upper_bound(int[] a, int key) { int lo = -1; int hi = a.length; while (hi - lo > 1) { int mid = (lo + hi) / 2; int midVal = a[mid]; if (midVal <= key) { lo = mid; } else { hi = mid; } } return hi; } public int[] getLIS(int[] x) { int n = x.length; int[] pred = new int[n]; int[] heaps = new int[n + 1]; Arrays.fill(heaps, Integer.MAX_VALUE); heaps[0] = Integer.MIN_VALUE; int[] no = new int[n + 1]; no[0] = -1; for (int i = 0; i < n; i++) { int j = upper_bound(heaps, x[i]); if (heaps[j - 1] < x[i]) { heaps[j] = x[i]; no[j] = i; pred[i] = no[j - 1]; } } for (int pos = n;; pos--) { if (heaps[pos] != Integer.MAX_VALUE) { int[] res = new int[pos]; for (int j = no[pos]; j != -1; j = pred[j]) { res[--pos] = x[j]; } return res; } } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
14739eadd8198e1ec6ba46c32f841d03
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.io.*; public class L { public static void main(String args[]) { Scanner sn=new Scanner(System.in); String str=sn.next(); int lo,hi,loc; lo=0; hi=-1; int ch=(int)'z'; while(ch>96) { loc=str.lastIndexOf(ch,str.length()-1); // System.out.println(lo+" "+hi); if(lo<=loc && loc!=-1) { hi=loc; // System.out.println(lo+" "+hi); for(int i=lo;i<=hi;i++) { if(str.charAt(i)==(char)ch) System.out.print((char)ch); } } lo=hi+1; ch--; } System.out.println(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ec941792230cf74681a1a885425da3e1
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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); TaskC solver = new TaskC(); solver.solve(in, out); out.close(); } } class TaskC { public void solve(InputReader in, PrintWriter out) { String s = in.next(); StringBuffer sb = new StringBuffer(); int last = 0; for (int i = s.length() - 1; i >= 0; --i) { int current = s.charAt(i); if (current >= last) { last = current; sb.append(s.charAt(i)); } } out.println(sb.reverse()); } } class InputReader { private BufferedReader reader; private 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 int nextInt() { return Integer.parseInt(next()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
837d4ff00d95ad82861b1ed3c9835eee
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; public class SearchSubstring2{ public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); String str = stdIn.next(); StringBuilder save = new StringBuilder(Character.toString(str.charAt(str.length()-1))); for(int i = str.length()-2; i >= 0; i--){ if( save.charAt(save.length()-1) <= str.charAt(i) ){ save.append(Character.toString(str.charAt(i))); } } save.reverse(); System.out.println(save.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e9b581adfb87c403c0be194551e030c0
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new C(filePath); } public C(String inputFile) { openInput(inputFile); readNextLine(); int n=line.length(); int [] lastId = new int[26]; int [] [] p = new int [n+1][26]; for(int i=0; i<n; i++) { p[i+1]=p[i].clone(); p[i+1][line.charAt(i)-'a']++; lastId[line.charAt(i)-'a']=i+1; } StringBuilder sb=new StringBuilder(); int a=0; for(int i=25; i>=0; i--) { if(p[n][i]-p[a][i]>0) { for(int j=0; j<p[n][i]-p[a][i]; j++) sb.append((char)('a'+i)); a=lastId[i]; } } System.out.println(sb); closeInput(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ce52f3d8952c0f6407e8ebc4470bd8d0
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.ArrayList; public class Template { public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); char[] kar = in.readLine().toCharArray(); ArrayList<Character> res = new ArrayList<Character>(); res.add(kar[0]); int size = 1; for (int i = 1; i < kar.length; i++) { if(kar[i]>res.get(size-1)){ int j = size-1; while(j >= 0 && kar[i]>res.get(j)) j--; j++; res.set(j, kar[i]); size = j+1; } else{ if(size < res.size()){ res.set(size++, kar[i]); } else { res.add(kar[i]); size++; } } } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); for (int i = 0; i < size; i++) { out.write(res.get(i)+""); } out.newLine(); out.flush(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
4ba64bc9facb8e4d0e297adafc878af1
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; public class Main { public void run() { Scanner sc = new Scanner(System.in); String str = sc.next(); StringBuilder st=new StringBuilder(); char min='a'; for(int i=str.length()-1;i>=0;i--){ if(min<=str.charAt(i)){ min=str.charAt(i); st.append(str.charAt(i)); } } pr(st.reverse()); } public static void main(String[] _) { new Main().run(); } public static void pr() { System.out.println(); } public static void pr(Object o) { System.out.println(o); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
034b15a53c0d2810490d9e5de35a82b3
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; import java.math.*; /** * * @author Magzhan */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { Scanner in = new Scanner(System.in); String s=in.nextLine(); char max=0; int index=-1,start=0; int j=0; while(index<s.length()-1){ int temp=0; max=0; for(int i=index+1;i<s.length();i++){ if((int)s.charAt(i)>=max){ max=(char)s.charAt(i); temp=i; } } index=temp; for(int i=start;i<s.length();i++){ if(s.charAt(i)==max){ System.out.print(max); } } start=index; j++; } } catch (Exception ex) { System.out.println(ex.toString()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
cf056229f1dfee387003e2acc7c8815f
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
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; public class C { public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String s = bf.readLine(); int n = s.length(); int[]m = new int[n]; for (int i = n-1; i >= 0; i--) { int t = s.codePointAt(i); if (i < n-1) m[i] = m[i+1]; m[i] = Math.max(m[i], t); } for (int i = 0; i < n; i++) { if (m[i]==s.codePointAt(i)) pw.print(s.charAt(i)); } pw.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
97e41d57138a36afa955ddfa7066d84b
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class TC { static ArrayList<Integer>[] loc; static String s; static void init() { loc = new ArrayList[ 26 ]; for( int i=0; i<s.length(); i++ ) { char c = s.charAt( i ); if( loc[ c - 'a' ] == null ) loc[ c - 'a'] = new ArrayList(); loc[ c - 'a'].add( i ); } } /* static int binarySearch( int lo, int hi, int MAXIND, ArrayList<Integer> arr ) { int min = Integer.MAX_VALUE; while( lo <= hi ) { int mid = ( lo + hi )/2; int ind = arr.get( mid ); if( ind < MAXIND ) lo = mid+1; else { min = Math.min( min, mid ); hi = mid-1; } } return min; } */ static void solve() { ArrayList<Character> str = new ArrayList(); String res = ""; int MAXIND = -1; for( int i=25; i>=0; i-- ) { if( loc[ i ] == null ) continue; for( int j=0; j<loc[ i ].size(); j++ ) { if( loc[ i ].get( j ) > MAXIND ) { MAXIND = loc[ i ].get( j ); str.add( ( char )( i + 'a') ); } } } for( char c : str ) { System.out.print( c ); } System.out.println(); } public static void main( String[] args ) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader( System.in )); s = br.readLine(); init(); solve(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
44d3049c42baa6ce173234ce16e01a79
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/26/11 * Time: 10:53 PM * To change this template use File | Settings | File Templates. */ public class TaskC { void run() { String s = next(); ArrayList<Integer> [] pos = new ArrayList[26]; for (int i = 0; i < 26; i++) pos[i] = new ArrayList<Integer>(); for (int i = 0; i < s.length(); i++) { pos[s.charAt(i) - 'a'].add(i); } StringBuilder builder = new StringBuilder(); int last = -1; for (int i = 25; i >= 0; i--) { for (int x : pos[i]) { if (x > last) { builder.append((char)('a' + i)); last = x; } } } System.out.println(builder.toString()); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskC().run(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
6781147282d046be7bc8ffffad5dfeb1
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int l = s.length(); int[] c = new int[256]; for (int i = 0; i < l; i++) { c[s.charAt(i)]++; } char m = 'z'; char curr; StringBuilder sb = new StringBuilder(); for (int i = 0; i < l; i++) { if (c[m] == 0) { while (c[m] == 0 && m >= 'a') m--; } curr = s.charAt(i); c[curr]--; if (curr == m) { sb.append(m); } } System.out.println(sb.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
cb3d0e25048bdd93a146846d3692a862
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] Args) { char[] s = ss().toCharArray(); StringBuilder b=new StringBuilder(s[s.length-1]+""); for (int i = s.length-2; i >=0; i--) { if (s[i]>=b.charAt(b.length()-1)) b.append(s[i]); } System.out.println(b.reverse().toString()); //System.out.println(b); } // ----------------------- Library ------------------------ static Scanner scan = new Scanner(System.in); static int INF = 2147483647; // finds GCD of a and b using Euclidian algorithm public int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } static List<String> toList(String[] a) { return Arrays.asList(a); } static String[] toArray(List<String> a) { String[] o = new String[a.size()]; a.toArray(o); return o; } static int[] pair(int... a) { return a; } static int si() { return scan.nextInt(); } static String ss() { return scan.nextLine(); } static int[] sai(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = si(); return a; } static String[] sas(int n) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) a[i] = ss(); return a; } static Object[][] _sm1(int r, int c) { Object[][] a = new Object[r][c]; for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) a[i][j] = scan.next(); return a; } static Object[][] _sm2(int r) { Object[][] a = new Object[r][3]; for (int i = 0; i < r; i++) a[i] = new Object[] { ss(), ss(), ss() }; return a; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
328961a98b1a0b4f99462f8ecb2c5611
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] Args) { char[] s = ss().toCharArray(); StringBuilder b=new StringBuilder(s[s.length-1]+""); for (int i = s.length-2; i >=0; i--) { if (s[i]>=b.charAt(b.length()-1)) b.append(s[i]); } System.out.println(b.reverse().toString()); } // ----------------------- Library ------------------------ static Scanner scan = new Scanner(System.in); static int INF = 2147483647; // finds GCD of a and b using Euclidian algorithm public int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } static List<String> toList(String[] a) { return Arrays.asList(a); } static String[] toArray(List<String> a) { String[] o = new String[a.size()]; a.toArray(o); return o; } static int[] pair(int... a) { return a; } static int si() { return scan.nextInt(); } static String ss() { return scan.nextLine(); } static int[] sai(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = si(); return a; } static String[] sas(int n) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) a[i] = ss(); return a; } static Object[][] _sm1(int r, int c) { Object[][] a = new Object[r][c]; for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) a[i][j] = scan.next(); return a; } static Object[][] _sm2(int r) { Object[][] a = new Object[r][3]; for (int i = 0; i < r; i++) a[i] = new Object[] { ss(), ss(), ss() }; return a; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
8a0f0d7932d72da1e05885580ed03552
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; public class C { public static void main(String[] args) throws Exception { new C().solve(); } void solve() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = in.readLine(); int idx = 0; char c = 'z'; StringBuilder ans = new StringBuilder(); while (true) { int tmp = 0; while (idx < str.length() && c >= 'a' && (tmp = str.indexOf(c, idx)) == -1) { c--; } if (c < 'a' || idx >= str.length()) { break; } else { ans.append(c); idx = tmp + 1; } } System.out.println(ans.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
9531047546c720648450dd75eec823d8
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static void init() { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); } static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { System.out.println(e); System.exit(1); } return tokenizer.nextToken(); } static byte nextByte() { return Byte.parseByte(nextToken()); } static short nextShort() { return Short.parseShort(nextToken()); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static float nextFloat() { return Float.parseFloat(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static void solve() { class Pair { char ch; int i; Pair(char ch, int i) { this.ch = ch; this.i = i; } } String str = nextToken(); Pair[] pairs = new Pair[str.length()]; for (int i = 0; i < str.length(); ++i) pairs[i] = new Pair(str.charAt(i), i); Arrays.sort(pairs, new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { int diff = o2.ch - o1.ch; if (diff == 0) return o1.i - o2.i; return diff; } }); StringBuilder builder = new StringBuilder(); int ind = pairs[0].i; for (int i = 0; i < pairs.length; i++) if (pairs[i].i >= ind) { builder.append(pairs[i].ch); ind = pairs[i].i; } writer.println(builder); } static void close() { try { reader.close(); writer.flush(); writer.close(); } catch (IOException e) { System.out.println(e); System.exit(1); } } public static void main(String[] args) { init(); solve(); close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
19857271f0cc108af985965d3f1800fb
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader r; r = new BufferedReader(new InputStreamReader(System.in)); //r = new BufferedReader(new FileReader(new File("in.txt"))); char[] c = r.readLine().toCharArray(); int n = c.length; char[] s = new char[n]; int sp = 0; s[0] = c[n - 1]; for (int i = n - 2; i >= 0; i--) { if ((int) c[i] >= (int) s[sp]) { s[++sp] = c[i]; } } StringBuffer sb = new StringBuffer(); for (int i = sp; i >= 0; i--) { sb.append(s[i]); } System.out.print(sb.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
f205194c36ea9671f97e33e4a05247c4
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Sergey Parkhomenko */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { String s=in.next(); int a[]=new int[1+(int)'z']; char max=s.charAt(0); int cmax=1,maxi=0; max=s.charAt(0); for (int i=1;i<s.length();i++) if (s.charAt(i)>max) { cmax=1; max=s.charAt(i); maxi=i; } else if (s.charAt(i)==max) { cmax++; maxi=i; } for (int i=0;i<cmax;i++) out.print(max); for (int i=maxi+1;i<s.length();i++) { char max1=max(s.substring(i,s.length())); int c=countMax(s.substring(i,s.length()),max1),k=s.lastIndexOf(max1); for (int j=0;j<c;j++) out.print(max1); i=k; } } public char max(String s) { char max=s.charAt(0); for (int i=0;i<s.length();i++) if (max<s.charAt(i)) max=s.charAt(i); return max; } public int countMax(String s,char max) { int c=0; for (int i=0;i<s.length();i++) if (s.charAt(i)==max) c++; return c; } } class InputReader { private BufferedReader reader; private 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 String nextLine() { if (tokenizer != null && tokenizer.hasMoreTokens()) { throw new RuntimeException(); } try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public char nextChar() { char chr='\n'; try { int i=reader.read(); if (i>=0) chr=(char)i; } catch (IOException e) { throw new RuntimeException(e); } return chr; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
a426ec8571a20e0ff8fe92493eb808c4
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { public static void main(String[] args) throws Exception { char[] c = inB.readLine().toCharArray(); int n = c.length; int curind = 0; for(char symb = 'z'; symb>='a'; symb--) { int last = curind; for(int i = curind; i<n; i++) { if(c[i] == symb) { out.print(symb); last = i; } } curind = last; } out.println(); out.flush(); // int n = nextInt(), m = nextInt(); // // int[] nn = new int[n+1]; // int[] mm = new int[m+1]; // // for(int i = 0; i<n+1; i++) { // nn[i] = nextInt(); // } // // for(int i = 0; i<m+1; i++) { // mm[i] = nextInt(); // } // // if(n > m && nn[0]*mm[0] > 0) // exit("Infinity"); // // if(n > m && nn[0]*mm[0] < 0) // exit("-Infinity"); // // if(n < m) // exit("0/1"); // // int a = Math.abs(nn[0]), b = Math.abs(mm[0]); // // out.println((nn[0]*mm[0] < 0 ? "-" : "") + (a/gcd(a,b)) + "/" + (b/gcd(a,b))); // out.flush(); } private static int gcd(int a, int b) { if(b == 0)return a; return gcd(b, a%b); } ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=false; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
dd5716872eca40719b1bdf576a98a842
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
//package div124; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); StringBuilder ans = solve(s); System.out.println(ans); } private static StringBuilder solve(String s) { if (s.length() == 0) return new StringBuilder(); else { char max = (char) (0); for (int i = 0; i < s.length(); i++) if (s.charAt(i) > max) max = s.charAt(i); int ind = s.lastIndexOf(max); StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) if (s.charAt(i) == max) sb.append(max); return sb.append(solve(s.substring(ind + 1))); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
baacd29f80ef5babe06b23ca7b5f6ce0
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class Main { public void solve( ) throws Throwable { int last = -1; char ch[ ] = in.next( ).toCharArray( ); StringBuilder ans = new StringBuilder( ); for ( char c = 'z'; c >= 'a'; --c ) { //debug( c, last ); for ( int i = last + 1; i < ch.length; ++i ) { if ( ch[ i ] == c ) { last = i; ans.append( c ); } } } out.println( ans ); } public void run( ) { in = new FastScanner( System.in ); out = new PrintWriter( new PrintStream( System.out ), true ); try { solve( ); out.close( ); System.exit( 0 ); } catch( Throwable e ) { e.printStackTrace( ); System.exit( -1 ); } } public void debug( Object...os ) { System.err.println( Arrays.deepToString( os ) ); } public static void main( String[ ] args ) { ( new Main( ) ).run( ); } private FastScanner in; private PrintWriter out; private static class FastScanner { private int charsRead; private int currentRead; private byte buffer[ ] = new byte[ 0x1000 ]; private InputStream reader; public FastScanner( InputStream in ) { reader = in; } public int read( ) { if ( charsRead == -1 ) { throw new InputMismatchException( ); } if ( currentRead >= charsRead ) { currentRead = 0; try { charsRead = reader.read( buffer ); } catch( IOException e ) { throw new InputMismatchException( ); } if ( charsRead <= 0 ) { return -1; } } return buffer[ currentRead++ ]; } public int nextInt( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( sign == -1 ) { c = read( ); } if ( c == -1 || !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int ans = 0; while ( !isWhitespace( c ) && c != -1 ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10 + num; c = read( ); } return ans * sign; } public long nextLong( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( sign == -1 ) { c = read( ); } if ( c == -1 || !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } long ans = 0; while ( !isWhitespace( c ) && c != -1 ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10 + num; c = read( ); } return ans * sign; } public boolean isWhitespace( int c ) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1; } public String next( ) { int c = read( ); StringBuffer ans = new StringBuffer( ); while ( isWhitespace( c ) && c != -1 ) { c = read( ); } if ( c == -1 ) { return null; } while ( !isWhitespace( c ) && c != -1 ) { ans.appendCodePoint( c ); c = read( ); } return ans.toString( ); } public String nextLine( ) { String ans = nextLine0( ); while ( ans.trim( ).length( ) == 0 ) { ans = nextLine0( ); } return ans; } private String nextLine0( ) { int c = read( ); if ( c == -1 ) { return null; } StringBuffer ans = new StringBuffer( ); while ( c != '\n' && c != '\r' && c != -1 ) { ans.appendCodePoint( c ); c = read( ); } return ans.toString( ); } public double nextDouble( ) { int c = read( ); while ( isWhitespace( c ) ) { c = read( ); } if ( c == -1 ) { throw new NullPointerException( ); } if ( c != '.' && c != '-' && !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int sign = c == '-' ? -1 : 1; if ( c == '-' ) { c = read( ); } double ans = 0; while ( c != -1 && c != '.' && !isWhitespace( c ) ) { if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10.0 + num; c = read( ); } if ( !isWhitespace( c ) && c != -1 && c != '.' ) { throw new InputMismatchException( ); } double pow10 = 1.0; if ( c == '.' ) { c = read( ); } while ( !isWhitespace( c ) && c != -1 ) { pow10 *= 10.0; if ( !( c >= '0' && c <= '9' ) ) { throw new InputMismatchException( ); } int num = c - '0'; ans = ans * 10.0 + num; c = read( ); } return ans * sign / pow10; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e5ab32208adc217ff9605ceb85a9b3c2
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class CFTest2 { static BufferedReader br; public static void main(String[]args){ br=new BufferedReader(new InputStreamReader(System.in)); try{ String line=readLine(); br.close(); int n=line.length(); int[]lp=new int[300]; Arrays.fill(lp,-1); int prv=-1; for(int i=0;i<n;i++){ lp[line.charAt(i)]=i; } StringBuilder sb=new StringBuilder(); for(int c='z'+1;c-->'a';){ if(lp[c]>prv){ for(int i=prv+1;i<=lp[c];i++){ if(line.charAt(i)==c)sb.append(line.charAt(i)); } prv=lp[c]; } } System.out.println(sb.toString()); //System.out.println(str); }catch(IOException e){ e.printStackTrace(); } } static public String readLine() throws IOException{ return br.readLine(); } static public long readlong() throws IOException{ return Long.parseLong(br.readLine()); } static public int readInt() throws IOException{ return Integer.parseInt(br.readLine()); } static public int[] readIntArr() throws IOException{ String[]str=br.readLine().split(" "); int arr[]=new int[str.length]; for(int i=0;i<arr.length;i++)arr[i]=Integer.parseInt(str[i]); return arr; } static public double[] readDoubleArr() throws IOException{ String[]str=br.readLine().split(" "); double arr[]=new double[str.length]; for(int i=0;i<arr.length;i++)arr[i]=Double.parseDouble(str[i]); return arr; } static public long[] readLongArr() throws IOException{ String[]str=br.readLine().split(" "); long arr[]=new long[str.length]; for(int i=0;i<arr.length;i++)arr[i]=Long.parseLong(str[i]); return arr; } static public double readDouble() throws IOException{ return Double.parseDouble(br.readLine()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
5f32b7ae491717d358f3abaaf836d5c3
train_003.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 &lt; p2 &lt; ... &lt; pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class C_124C { static class A implements Comparable<A>{ int x,i; public int compareTo(A o) { if(this.x<o.x || this.x==o.x && this.i>o.i) return 1; return 0; } } public static void main(String[] args) throws IOException { InputStreamReader is = new InputStreamReader(System.in); A s[]= new A [100005]; s[0] = new A(); s[0].x = is.read(); s[0].i =0; int k = 0; while(is.ready()){ s[++k] = new A(); s[k].x = is.read(); s[k].i = k; } k-=2; Arrays.sort(s,0,k+1); int max = s[0].x; int ind = s[0].i-1; for (int i = 0; i <= k; i++) { if(max==s[i].x && ind<s[i].i){ System.out.print((char) s[i].x); ind = s[i].i; }else{ if(ind < s[i].i) { max = s[i].x; ind = s[i].i; System.out.print((char) max); } } } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "implementation", "sortings", "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
a1975df612e099d4cdd2d9c9bbd8eeec
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.io.*; import java.math.BigInteger; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } public static void main(String [] argv) { //String filePath="input.txt"; String filePath=null; if(argv.length>0)filePath=argv[0]; new C(filePath); } public C(String inputFile) { openInput(inputFile); StringBuilder sb = new StringBuilder(); readNextLine(); int N=NextInt(); int M=NextInt(); int [] p = new int[4]; int prevd=-1, prevh=-1; int maxh=0; for(int i=0; i<M; i++) { readNextLine(); int d=NextInt(); int h=NextInt(); if(i==0) { prevd=d; prevh=h; maxh=h+d-1; if(i==M-1) { maxh = Math.max(maxh, prevh+N-d); } continue; } if(Math.abs(prevh-h)>Math.abs(prevd-d)) { maxh=-1; break; } int D=d-prevd; int min=Math.min(h, prevh); int max=Math.max(h, prevh); int diff=max-min; min+=diff; D-=diff; maxh = Math.max(maxh, max+D/2); prevh=h; prevd=d; if(i==M-1) { maxh = Math.max(maxh, prevh+N-d); } } if(maxh<0)System.out.println("IMPOSSIBLE"); else System.out.println(maxh); closeInput(); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
d37ac5b23ccf268c4b16e5965078ad05
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.*; import java.io.*; public class man { public static void main(String args[]) throws IOException{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String s[]=in.readLine().split(" "); int n=Integer.parseInt(s[0]); int m=Integer.parseInt(s[1]); int arr[][]=new int[m][2]; int i=0; while(i<m) { String s1[]=in.readLine().split(" "); arr[i][0]=Integer.parseInt(s1[0]); arr[i][1]=Integer.parseInt(s1[1]); i++; } int t=1; int max=0; for(i=1;i<m&&t!=0;i++) { int tem=Math.abs(arr[i][1]-arr[i-1][1]); int dis=arr[i][0]-arr[i-1][0]; if(dis<tem) { t=0; System.out.println("IMPOSSIBLE"); break; } else { int ans=(dis+arr[i][1]+arr[i-1][1])/2; if(ans>max) max=ans; } } int ans=n-arr[m-1][0]; ans=ans+arr[m-1][1]; if(ans>max) max=ans; int ans2=arr[0][0]+arr[0][1]-1; if(ans2>max) max=ans2; if(t==1) System.out.println(max); }}
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
6f9513e201a12bf07c29299f4c7b1eb2
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
/* * Code Author: Jayesh Udhani * Dhirubhai Ambani Institute of Information and Communication Technology (DA-IICT ,Gandhinagar) * 2nd Year ICT BTECH Student */ import java.io.*; import java.util.*; public class hike { public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code Starts Here---------- int n,m,i,max=Integer.MIN_VALUE; n=in.nextInt(); m=in.nextInt(); int[] d=new int[m]; int[] hd=new int[m]; for(i=0;i<m;i++) { d[i]=in.nextInt(); hd[i]=in.nextInt(); } if((d[0]-1)+hd[0]>max) max=(d[0]-1)+hd[0]; for(i=0;i<m-1;i++) { if(Math.abs(d[i+1]-d[i])==Math.abs(hd[i+1]-hd[i])) { if(Math.max(hd[i+1],hd[i])>max) max=Math.max(hd[i+1],hd[i]); } else if(Math.abs(d[i+1]-d[i])<Math.abs(hd[i+1]-hd[i])) { System.out.println("IMPOSSIBLE"); return; } else { int x=(d[i+1]-d[i]-1)-Math.abs(hd[i+1]-hd[i]); if(x%2==0) { int t=x/2 + Math.max(hd[i+1], hd[i]); if(t>max) max=t; } else { int t= (x+1)/2 + Math.max(hd[i+1], hd[i]); if(t>max) max=t; } } } if((n-d[m-1])+hd[m-1]>max) max=(n-d[m-1])+hd[m-1]; System.out.println(max); out.close(); //---------------The End——————————————————— } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
9f5197e50fa9bd9ba578963f6a3722b5
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
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 */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int[] di = new int[m]; int[] hd = new int[m]; for (int i = 0; i < m; ++i) { di[i] = in.ni(); hd[i] = in.ni(); } int max = di[0] - 1 + hd[0]; for (int i = 1; i < m; ++i) { int days = di[i] - di[i - 1]; int valueChange = Math.abs(hd[i] - hd[i - 1]); if (valueChange > days) { out.println("IMPOSSIBLE"); return; } max = Math.max(max, Math.max(hd[i], hd[i - 1]) + (days - valueChange) / 2); } max = Math.max(max, hd[m - 1] + (n - di[m - 1])); out.println(max); } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String n() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int ni() { return Integer.parseInt(n()); } } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
3e8a3a6f1a82b2ff19fbc79f4d20d098
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.Scanner; public class Tester { public static void main(String args[]){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); long total; long d; long h; long x = 0; long y = 0; long dl = 0; long hl = 0; int hight; int max = 0; int flag = 0; for(int i=0;i<m;i++){ d = scan.nextInt(); h = scan.nextInt(); if(i==0){ x=d; y=h; } if(i!=0){ if((d-dl<h-hl || d-dl<hl-h)&& flag==0){ System.out.println("IMPOSSIBLE"); flag++; break; } } if(i!=0) total = hl + d - dl; else total = d; int count = 0; int t = (int) total; while(true){ if(total<=h) break; total = total - 2; count++; } hight = t - count; if(hight>max){ max = hight; } dl = d; hl = h; } if(n!=dl && hl+(n-dl)>max) max = (int) (hl+n-dl); if((x+y-1)>max){ max = (int) (x+y-1); } if(flag!=1){ System.out.println(max); } } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
695fc1410d33102708f251b56a98e9a2
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.ReadOnlyBufferException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; public class R300 { public static InputReader in; public static PrintWriter out; public static Random ra = new Random(0); public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; in = new InputReader(inputStream); out = new PrintWriter(outputStream, true); // CuttingBanner(); // QuasiBinary(); TouristsNotes(); out.close(); } public static void TouristsNotes() { long days = in.nextInt(); int m = in.nextInt(); long[] d = new long[m]; long[] h = new long[m]; for (int i = 0; i < m; i++) { d[i] = in.nextLong(); h[i] = in.nextLong(); } boolean valid = true; long max = 0; for (int i = 1; i < m; i++) { long xa = d[i-1]; long xb = d[i]; long ca = h[i-1] - xa; long cb = h[i] + xb; long maxX = (cb - ca) / 2; if (xa <= maxX && maxX <= xb) { // valid long maxY = maxX + ca; max = Math.max(max, maxY); } else { valid = false; } } // start and end max = Math.max(max, h[0] + d[0] - 1); max = Math.max(max, h[m-1] + (days-d[m-1])); if (valid) { System.out.println(max); } else { System.out.println("IMPOSSIBLE"); } } public static void QuasiBinary() { int a = in.nextInt(); char[] x = (a + "").toCharArray(); ArrayList<Integer> nums = new ArrayList<>(); while (true) { char[] out = new char[x.length]; int size = 0; for (int i = 0; i < x.length; i++) { if (x[i] >= '1') { out[i] = '1'; x[i]--; size++; } else { out[i] = '0'; } } if (size == 0) { break; } nums.add(Integer.parseInt(new String(out))); } System.out.println(nums.size()); for (int i = 0; i < nums.size(); i++) { System.out.print(nums.get(i) + " "); } } public static void CuttingBanner() { char[] code = "CODEFORCES".toCharArray(); char[] s = in.next().toCharArray(); boolean valid = false; for (int start = 0; start < s.length; start++) { for (int end = start; end < s.length; end++) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length; i++) { if (i < start || i > end) { sb.append(s[i]); } } // System.out.println(sb.toString()); if (sb.toString().equals(new String(code))) { valid = true; } } } if (valid) { System.out.println("YES"); } else { System.out.println("NO"); } } public static class InputReader { public BufferedReader r; public StringTokenizer st; public InputReader(InputStream s) {r = new BufferedReader(new InputStreamReader(s), 32768); st = null;} public String next() {while (st == null || !st.hasMoreTokens()) {try {st = new StringTokenizer(r.readLine());} catch (IOException e) {throw new RuntimeException(e);}} 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 long[] nextLongArray(int n) {long[] a = new long[n]; for (int i = 0; i < a.length; i++) {a[i] = this.nextLong();} return a;} public int[] nextIntArray(int n) {int[] a = new int[n]; for (int i = 0; i < a.length; i++) {a[i] = this.nextInt();} return a;} } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
1e68deb711638909976f0e515cb40208
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.*; import java.io.*; public class CF_rnd300C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int m = nextInt(); int[] d = new int[m]; int[] h = new int[m]; for(int i = 0; i < m; i++) { d[i] = nextInt(); h[i] = nextInt(); } for(int i = 0; i < m - 1; i++) { int diffD = d[i + 1] - d[i]; int diffH = Math.abs(h[i + 1] - h[i]); if(diffD < diffH) { out.print("IMPOSSIBLE"); return; } } int res = (d[0] - 1) + h[0]; for(int i = 0; i < m - 1; i++) { int tp = hp(d[i], h[i], d[i + 1], h[i + 1]); res = Math.max(res, tp); } res = Math.max(res, h[m - 1] + n - d[m - 1]); out.print(res); } public int hp(int d1, int h1, int d2, int h2) { int x = (h2 - h1 + d1 + d2) / 2; int res = 0; for(int dx = -2; dx <= 2; dx++) { if(dx + x >= d1 && dx + x <= d2) { int y = Math.min(x + dx + h1 - d1, d2 + h2 - (x + dx)); res = Math.max(res, y); } } return res; } public CF_rnd300C() 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 CF_rnd300C(); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
6dd614c7dffd936091c9e5d82511d60a
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
/** * Created by gosugdr on 4/26/15. */ import java.util.*; import java.io.*; public class C { FastScanner in; PrintWriter out; class Point { int d; int h; public Point(int d, int h) { this.d = d; this.h = h; } public Point() { } @Override public String toString() { return "Point{" + "d=" + d + ", h=" + h + '}'; } } public void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); Point[] points = new Point[m + 2]; points[0] = null; points[m + 1] = null; int max = Integer.MIN_VALUE; for (int i = 0; i < m; i++) { int d = in.nextInt(); int h = in.nextInt(); max = Math.max(max, h); points[i + 1] = new Point(d, h); } if (points[1].d != 1) { points[0] = new Point(1, points[1].d - 1 + points[1].h); } if (points[m].d != n) { points[m + 1] = new Point(n, n - points[m].d + points[m].h); } // for (int i = 0; i < points.length; i++) { // out.println(points[i]); // } for (int i = 0; i < m + 1; i++) { if (points[i] == null || points[i + 1] == null) { continue; } if (Math.abs(points[i].h - points[i + 1].h) > points[i + 1].d - points[i].d) { out.println("IMPOSSIBLE"); return; } // out.println(points[i].h + " " +points[i].d + " " + points[i + 1].h + " " + points[i + 1].d + " " + (-Math.abs(points[i].h - points[i + 1].h)) + " " + ( (points[i + 1].d - points[i].d))); max = Math.max(max, Math.max(points[i].h, points[i + 1].h) +( - Math.abs(points[i].h - points[i + 1].h) + (points[i + 1].d - points[i].d)) / 2); } out.println(max); } // 0 1 2 3 4 4 3 2 1 0 public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new C().run(); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
f74966ff7178091aabd157a6a37ffd44
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TouristNotes1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyScanner input = new MyScanner(); int n = input.nextInt(); int d = input.nextInt(); int[][] arr = new int[d][2]; for(int i=0; i<d;i++){ arr[i][0] = input.nextInt(); arr[i][1] = input.nextInt(); } int max = 0; for(int i=1; i<d;i++){ if(Math.abs(arr[i][1]-arr[i-1][1])>arr[i][0]-arr[i-1][0]){ System.out.println("IMPOSSIBLE"); return; } max = Math.max(max,arr[i][1]); } max = Math.max(arr[0][0]+arr[0][1]-1,max); for(int i=1; i<d;i++){ if(arr[i][1]>arr[i-1][1]){ int z = arr[i][1]-arr[i-1][1]; int p = arr[i][0]-arr[i-1][0]; max = Math.max(arr[i][1]+(p-z)/2,max); } else{ int z = arr[i-1][1]-arr[i][1]; int p = arr[i][0]-arr[i-1][0]; max = Math.max(arr[i-1][1]+(p-z)/2,max); } } max = Math.max(max, arr[d-1][1]+(n-arr[d-1][0])); System.out.println(max); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
fd2a1086f1c65e9ac9833ff670b97982
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStream; import java.io.InputStreamReader; /** * Built using CHelper plug-in * Actual solution is at the top * @author Artyom Korzun */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { long n = in.nextInt(); long m = in.nextInt(); long prevD = in.nextInt(); long prevH = in.nextInt(); long answer = prevH + prevD - 1; boolean answerPossible = true; for (long i = 1; i < m; i++) { long d = in.nextInt(); long h = in.nextInt(); long dm = prevD + Math.abs(h - prevH); if (dm > d) { answerPossible = false; break; } else { long maxDeltaH = (d - dm) / 2; answer = Math.max(answer, Math.max(h, prevH) + maxDeltaH); } prevD = d; prevH = h; } if (answerPossible) answer = Math.max(answer, prevH + n - prevD); out.print(answerPossible ? answer : "IMPOSSIBLE"); } } class FastScanner { private final BufferedReader reader; private StringTokenizer tokenizer; public FastScanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } private String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
0c127a92565c65485e1f192bec694e05
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class cf { static int n; static int m; static Integer arr[]; public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Scanner sc=new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); int dprev=sc.nextInt(); int hprev=sc.nextInt(); int ans=hprev+(dprev-1); m--; while(m-->0) { int d=sc.nextInt(); int h=sc.nextInt(); if(d-dprev<Math.abs(h-hprev)) { System.out.println("IMPOSSIBLE"); System.exit(0); } ans=Math.max(ans,(d-dprev-Math.abs(h-hprev))/2+Math.max(h,hprev)); dprev=d; hprev=h; } ans=Math.max(ans,n-dprev+hprev); System.out.println(ans); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
87334f3e657f8ad43e23526a64fdb834
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[]a= new int[m]; int[]b = new int[m]; for (int i=0;i<m;i++) { a[i]=in.nextInt(); b[i]=in.nextInt(); } int max=0; boolean check =true; for (int i =0;i<m-1;i++) { int cntr=a[i]; int value = b[i]; if (Math.abs(b[i+1]-b[i])>a[i+1]-a[i]) { check=false; break; } while (cntr<=a[i+1]&&a[i+1]-cntr>=value-b[i+1]) { max=Math.max(max,value); cntr++; value++; } } max=Math.max(max,(a[0]-1)+b[0]); max=Math.max(max,n-a[m-1]+b[m-1]); out.printLine(check?max:"IMPOSSIBLE"); out.flush(); } } class pair implements Comparable { int key; int value; public pair(Object key, Object value) { this.key = (int)key; this.value=(int)value; } @Override public int compareTo(Object o) { pair temp =(pair)o; return key-temp.key; } } class Graph { int n; ArrayList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
6fd2182b4cb572f6a5bba96abf525dc9
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] l = bf.readLine().split(" "); long n = Integer.parseInt(l[0]); int m = Integer.parseInt(l[1]); long nums[][] = new long[2][m]; for (int i = 0; i < m; i++) { l = bf.readLine().split(" "); nums[0][i] = Integer.parseInt(l[0]); nums[1][i] = Integer.parseInt(l[1]); } long max = nums[1][0] + nums[0][0] - 1, d1, d2, h1, h2, need, have, left; for (int i = 0; i < m - 1; i++) { d1 = nums[0][i]; d2 = nums[0][i + 1]; h1 = nums[1][i]; h2 = nums[1][i + 1]; need = Math.abs(h2 - h1); have = d2 - d1; if (need > have) { System.out.println("IMPOSSIBLE"); return; } else { left = have - need; max = Math.max(max, Math.max(h1, h2) + left / 2); } } max = Math.max(max, n - nums[0][m - 1] + nums[1][m - 1]); System.out.println(max); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
945059e340e381630cf99d9fe855b71d
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.*; public class SolutionC { public static void main(String args[]){ Scanner s1=new Scanner(System.in); int n=s1.nextInt(); int r=s1.nextInt(); List<Integer> day=new ArrayList<Integer>(); List<Integer> height=new ArrayList<Integer>(); long max=-1; for(int i=0;i<r;i++){ day.add(s1.nextInt()); height.add(s1.nextInt()); } if(n-day.get(r-1)+height.get(r-1)>max){ max=n-day.get(r-1)+height.get(r-1); } if(day.get(0)+height.get(0)-1>max){ max=day.get(0)+height.get(0)-1; } for(int i=r-1;i>0;i--){ long difD=day.get(i)-day.get(i-1); long difH=Math.abs(height.get(i)-height.get(i-1)); if(difH>difD){ max=-1; break; } else{ long tmp=(height.get(i)+height.get(i-1)+difD)/2; if(tmp>max) max=tmp; } } if(max==-1) System.out.println("IMPOSSIBLE"); else System.out.println(max); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
482205105e1be9742d1a298a398fe930
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(), m = scn.nextInt(); int maxHeight = 0; int lastDay = scn.nextInt(), lastHeight = scn.nextInt(); int firstHeight = lastDay - 1 + lastHeight; maxHeight = maxHeight > firstHeight ? maxHeight : firstHeight; for(int i = 1; i < m; i++) { int currDay = scn.nextInt(), currHeight = scn.nextInt(); if(Math.abs(currHeight - lastHeight) > currDay - lastDay) { System.out.println("IMPOSSIBLE"); return; } int maxStart = currHeight > lastHeight ? currHeight : lastHeight; int days = currDay - lastDay - Math.abs(currHeight - lastHeight); int height = days / 2 + maxStart; maxHeight = maxHeight > height ? maxHeight : height; lastDay = currDay; lastHeight = currHeight; } int finalHeight = n - lastDay + lastHeight; maxHeight = maxHeight > finalHeight ? maxHeight : finalHeight; System.out.println(maxHeight); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
75e6bb902c382aeb78305b55551ad80b
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.InputMismatchException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] d = new int[m]; int[] h = new int[m]; for (int i = 0; i < m; ++i) { d[i] = in.nextInt(); h[i] = in.nextInt(); } int res = Math.max(h[0] + d[0] - 1, h[m - 1] + n - d[m - 1]); for (int i = 1; i < m; ++i) { int cntD = d[i] - d[i - 1]; int difH = Math.abs(h[i] - h[i - 1]); if (difH > cntD) { out.println("IMPOSSIBLE"); return; } int maxH = Math.max(h[i], h[i - 1]); res = Math.max(res, maxH + (cntD - difH) / 2); } out.println(res); } } class InputReader { BufferedReader in; StringTokenizer st; public InputReader(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); eat(""); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (!st.hasMoreTokens()) eat(nextLine()); return st.nextToken(); } public String nextLine() { try { return in.readLine(); } catch (IOException e) { throw new InputMismatchException(); } } public void eat(String str) { if (str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
187f2d2abe2427f5534099b74de30ae9
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.InputMismatchException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] d = new int[m]; int[] h = new int[m]; for (int i = 0; i < m; ++i) { d[i] = in.nextInt(); h[i] = in.nextInt(); } int res = h[0]; if (d[0] != 1) res = Math.max(res, h[0] + d[0] - 1); if (d[m - 1] != n) res = Math.max(res, h[m - 1] + n - d[m - 1]); for (int i = 1; i < m; ++i) { int cntD = d[i] - d[i - 1] - 1; int difH = Math.abs(h[i] - h[i - 1]); if (difH > cntD + 1) { out.println("IMPOSSIBLE"); return; } int maxH = Math.max(h[i], h[i - 1]); res = Math.max(res, maxH + (cntD - difH + 1) / 2); } out.println(res); } } class InputReader { BufferedReader in; StringTokenizer st; public InputReader(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); eat(""); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (!st.hasMoreTokens()) eat(nextLine()); return st.nextToken(); } public String nextLine() { try { return in.readLine(); } catch (IOException e) { throw new InputMismatchException(); } } public void eat(String str) { if (str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
26b2008d19bfcb59eecd1c36f8a1bf9f
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.InputStream; import java.util.NoSuchElementException; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; /** * 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); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int days = in.readInt(); int n = in.readInt(); int[] d = new int[n]; int[] h = new int[n]; for (int i = 0; i < n; i++) { d[i] = in.readInt(); h[i] = in.readInt(); } int best = Math.max(h[0] + (d[0] - 1), h[n - 1] + (days - d[n - 1])); for (int i = 1; i < n; i++) { int dd = Math.abs(d[i] - d[i - 1]); int minH = Math.min(h[i], h[i - 1]); int maxH = Math.max(h[i], h[i - 1]); int res = f(dd, minH, maxH); if (res == -1) { out.printLine("IMPOSSIBLE"); return; } best = Math.max(best, res); } out.printLine(best); } private int f(int dd, int minH, int maxH) { if (Math.abs(minH - maxH) > dd) { return -1; } int x = dd - Math.abs(minH - maxH); return maxH + x / 2; } } 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 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 void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
afafc1c564af3b0f544ef52b42f56a12
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.*; import java.io.*; public class Class{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int max = 0; int x1 = 0; int x2 = 0; int y1 = 0; int y2 = 0; st = new StringTokenizer(br.readLine()); x2 = Integer.parseInt(st.nextToken()); y2 = Integer.parseInt(st.nextToken()); x1 = x2; y1 = y2; max = y2 + (x1-1); for(int i=1; i<m; i++){ st = new StringTokenizer(br.readLine()); x1 = x2; y1 = y2; x2 = Integer.parseInt(st.nextToken()); y2 = Integer.parseInt(st.nextToken()); if(Math.abs(((double)y2-y1)/(x2-x1))>1){ System.out.println("IMPOSSIBLE"); return; }else if(y2>=y1){ max = Math.max(max, y2+(x2-x1+y1-y2)/2); }else{ max = Math.max(max, y1+(x2-x1+y2-y1)/2); } } max = Math.max(max, y2+(n-x2)); System.out.print(max); } static class Pair implements Comparable<Pair>{ int start; int end; public Pair(int start, int end){ this.start = start; this.end = end; } public int compareTo(Pair p){ if(p.start>this.start)return -1; else if(p.start==this.start)return 0; return 1; } } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
2a28e60f2503e16192bdddc1812fcbe0
train_003.jsonl
1430064000
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String ars[]) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); int m = sc.nextInt(); long max = 0; long[][] ar = new long[m][2]; for (int i = 0; i < m; i++) { ar[i][0] = sc.nextLong(); ar[i][1] = sc.nextLong(); if (max < ar[i][1]) { max = ar[i][1]; } if (i > 0) { if (Math.abs(ar[i][0] - ar[i - 1][0]) < Math.abs(ar[i][1] - ar[i - 1][1])) { System.out.println("IMPOSSIBLE"); return; } /* long d_v = Math.abs(ar[i][1] - ar[i - 1][1]); long d_p = (ar[i][0] - ar[i - 1][0] - d_v) / 2; if (max < ar[i][1] + d_p) { max = ar[i][1] + d_p; }*/ long d = (ar[i][1] + ar[i - 1][1] + ar[i][0] - ar[i - 1][0]) / 2; if (max < d) { max = d; } } else { max = ar[0][1] + ar[0][0] - 1; } } if (max < ar[m - 1][1] + n - ar[m - 1][0]) { max = ar[m - 1][1] + n - ar[m - 1][0]; } System.out.println(max); } }
Java
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
2 seconds
["2", "IMPOSSIBLE"]
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
Java 8
standard input
[ "greedy", "math", "implementation", "binary search", "brute force" ]
77b5bed410d621fb56c2eaebccff5108
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
1,600
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
standard output
PASSED
7cbcfb776a1b2305c33225bf20040785
train_003.jsonl
1365796800
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.
256 megabytes
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict Not sended * @url <https://codeforces.com/problemset/problem/291/B> * @category ? * @date 9/06/2020 **/ import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CF291B { public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null && !ln.equals(""); ) { StringBuilder sb = new StringBuilder(); char[] s = ln.toCharArray(); boolean isString = false; StringBuilder lexeme = new StringBuilder(); for (int i = 0; i < s.length; i++) { if (s[i] == '"' && isString) { isString = false; sb.append("<").append(new String(lexeme)).append(">\n"); lexeme = new StringBuilder(); } else if (s[i] == '"') { isString = true; } else if (s[i] == ' ' && !isString) { if (lexeme.length() > 0) { sb.append("<").append(new String(lexeme)).append(">\n"); lexeme = new StringBuilder(); } } else if (s[i] != ' ' || (s[i] == ' ' && isString)) lexeme.append(s[i]); } if(lexeme.length()>0) sb.append("<").append(new String(lexeme)).append(">\n"); System.out.print(new String(sb)); } } }
Java
["\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"", "firstarg second \"\""]
1 second
["&lt;RUn.exe O&gt;\n&lt;&gt;\n&lt; 2ne, &gt;\n&lt;two!&gt;\n&lt;.&gt;\n&lt; &gt;", "&lt;firstarg&gt;\n&lt;second&gt;\n&lt;&gt;"]
null
Java 11
standard input
[ "implementation", "*special", "strings" ]
6c7858731c57e1b24c7a299a8eeab373
The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.
1,300
In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "&lt;" (less) character to the left of your lexemes and the "&gt;" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.
standard output
PASSED
65f6346e92fae23bb11370d8b4f1c7c8
train_003.jsonl
1365796800
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.
256 megabytes
import java.util.*; import java.io.*; public class vv{ public static void main(String[] args) throws IOException{ // Scanner no=new Scanner(System.in); BufferedReader no=new BufferedReader(new InputStreamReader(System.in)); String s=no.readLine(); s.replaceAll("\\s"," "); int i; for(i=0;i<s.length();i++){ if(s.charAt(i)=='"'){ // System.out.println("^"); for(int j=i+1;j<s.length();j++){ //System.out.println(j); if(s.charAt(j)=='"'){ if(j-i==1){ System.out.println("<>"); i=j; break; } else{ //System.out.println(i+1+" "+j); System.out.println("<"+s.substring(i+1,j)+">"); i=j; break; } } } } else if(s.charAt(i)!=' '){ // System.out.println(i); outer:for(int y=i;y<s.length();y++){ if(s.charAt(y)=='!'||s.charAt(y)=='?'||s.charAt(y)=='.'||s.charAt(y)==','||Character.isDigit(s.charAt(y))||Character.isLetter(s.charAt(y))&&y!=s.length()-1){ for(int y1=i;y1<s.length();y1++){ // System.out.println(s.charAt(y1)); if(s.charAt(y1)==' '||y1==s.length()-1){ if(y1==s.length()-1&&s.charAt(y1)!=' '){ y1++; } // System.out.println("&"); System.out.println("<"+s.substring(y,y1)+">"); i=y1; break outer; } } } // System.out.println(s.charAt(y)); else if(s.charAt(y)!=' '){ //System.out.println("t"); System.out.println("<"+s.charAt(y)+">"); break outer; } } } } } }
Java
["\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"", "firstarg second \"\""]
1 second
["&lt;RUn.exe O&gt;\n&lt;&gt;\n&lt; 2ne, &gt;\n&lt;two!&gt;\n&lt;.&gt;\n&lt; &gt;", "&lt;firstarg&gt;\n&lt;second&gt;\n&lt;&gt;"]
null
Java 11
standard input
[ "implementation", "*special", "strings" ]
6c7858731c57e1b24c7a299a8eeab373
The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.
1,300
In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "&lt;" (less) character to the left of your lexemes and the "&gt;" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.
standard output
PASSED
17b7d9de6da3e5be72dbfe87c4f44061
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main extends Reader { public static void main(String[] args) throws IOException { int n = ni(), a = ni(), b = ni(), k = ni(), p = 0, sum = 0; String s = ns()+"1"; int len[] = new int[n]; int pos[] = new int[n]; int m = 0; for (int i=0; i<=n; i++) { if (s.charAt(i) == '0') continue; // i (i-p)/b int num = (i - p) / b; sum += num; //System.out.println(num+" "+p+" "+i); len[m] = num; pos[m++] = p; p = i+1; } List<Integer> arr = new ArrayList<>(); for (; sum>=a; sum--) { while (m>0 && len[m-1]==0) m--; len[m-1]--; arr.add(pos[m-1] += b); } System.out.println(arr.size()); for (Integer i : arr) { System.out.print(i+" "); } } } class Reader { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); /** call this method to change InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input) ); } /** get next word */ static String ns() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int ni() throws IOException { return Integer.parseInt( ns() ); } static double nd() throws IOException { return Double.parseDouble( ns() ); } static long nl() throws IOException { return Long.valueOf( ns() ); } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
8aef521732c566fbfa7b6171a4f0bbc9
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF737B extends PrintWriter { CF737B() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return a; } int m = 1 << 7; byte[] cc = new byte[m]; int read() { byte c = 0; while (c <= 32) c = getc(); int n = 0; while (c > 32) { if (n == m) cc = Arrays.copyOf(cc, m <<= 1); cc[n++] = c; c = getc(); } return n; } byte[] nextBytes() { int n = read(); return Arrays.copyOf(cc, n); } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF737B o = new CF737B(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int k = sc.nextInt(); byte[] cc = sc.nextBytes(); int[] ll = new int[k + 1]; int[] rr = new int[k + 1]; k = 0; int c = 0; for (int i = 0, p = -1; i <= n; i++) if (i == n || cc[i] == '1') { ll[k] = p + 1; rr[k] = i - 1; c += (rr[k] - ll[k] + 1) / b; k++; p = i; } k = 0; println(c - a + 1); while (c >= a) { while (rr[k] - ll[k] + 1 < b) k++; ll[k] += b; print(ll[k] + " "); c--; } println(); } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
98d257d6c2d60c47ebb6b54515d22d9e
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class B2 { public static void main(String[] args) { FastScanner $ = new FastScanner(); int gridWidth = $.nextInt(); int numShips = $.nextInt(); int shipWidth = $.nextInt(); int k = $.nextInt(); alreadyHit = new boolean[gridWidth]; String str = $.next(); for (int i = 0; i < gridWidth; i++) { alreadyHit[i] = str.charAt(i) == '1'; } // int low = 0; // int high = gridWidth; // while (low < high) { // int mid = (low + high) / 2; // boolean ok = check(gridWidth, numShips, shipWidth, mid); // if (ok) { // high = mid; // } else { // low = mid + 1; // } // } // System.err.println(check(gridWidth, numShips, shipWidth, 0)); check(gridWidth, numShips, shipWidth); StringBuilder sb = new StringBuilder(); sb.append(assignment.size()).append('\n'); for (int i = 0; i < assignment.size(); i++) { if (i > 0) sb.append(' '); sb.append(assignment.get(i)); } System.out.println(sb); } static boolean[] alreadyHit; static List<Integer> assignment; static void check(int gridWidth, int numShips, int shipWidth) { int numShipsAlive = 0; int curRun = 0; assignment = new ArrayList<>(); for (int i = 0; i < gridWidth; i++) { if (alreadyHit[i]) { curRun = 0; } else { curRun++; if (curRun == shipWidth) { if (numShipsAlive + 1 >= numShips) { assignment.add(i + 1); curRun = 0; } else { numShipsAlive++; curRun = 0; } } } } } static void shuffle(int[] arr) { Random rng = new Random(); int length = arr.length; for (int idx = 0; idx < arr.length; idx++) { int toSwap = idx + rng.nextInt(length-idx); int tmp = arr[idx]; arr[idx] = arr[toSwap]; arr[toSwap] = tmp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
a3c38f186cb7f3ca183894f883872653
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.io.*; import java.util.*; public class ProblemB { public static void main(String[] args) { // TODO Auto-generated method stub FastScanner input = new FastScanner(); int length = input.nextInt(); int numShips = input.nextInt(); int lengthOfShips = input.nextInt(); int numberOfShotsAlreadyMade = input.nextInt(); boolean[] attacked = new boolean[length]; String in = input.next(); for(int a = 0; a < length; a++){ attacked[a] = in.charAt(a)=='1'; } ArrayList<Integer> spots = new ArrayList<Integer>(); int conseq = 0; for(int a = 0; a < length; a++){ if(attacked[a] == false){ conseq++; } else{ conseq = 0; } if(conseq == lengthOfShips){ conseq = 0; spots.add(a); } } int numToShoot = Math.max(spots.size()-numShips+1, 0); StringBuilder output = new StringBuilder(); output.append(numToShoot + "\n"); for(int a = 0; a < numToShoot; a++){ output.append((spots.get(a)+1) + " "); } output.append("\n"); System.out.print(output); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
8776e525efb8ded0aa3ecc6f71635ab1
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.*; import java.util.*; import java.util.List; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { String filename = ""; if (filename.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(filename + ".out"); } } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int a = readInt(); int b = readInt(); int k = readInt(); char[] s = readString().toCharArray(); int cnZeros = 0; int canPlace = 0; ArrayList<Integer> answer = new ArrayList<>(); int ind = 1; for (char x : s) { if (x == '0') { cnZeros++; } else { cnZeros = 0; } if (cnZeros == b) { canPlace++; cnZeros = 0; answer.add(ind); } ind++; } out.println(canPlace - a + 1); for (int i = 0; i <= canPlace - a; i++) { out.print(answer.get(i) + " "); } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
5ecf715c7a2b5832102d8513cc8e6e0d
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CT2B { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; static class Sort implements Comparable<Sort> { int ind, a; @Override public int compareTo(Sort o) { return a - o.a; } public Sort(int i, int an) { ind = i; a = an; } } static int n, a, b, k; static char[] c; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); pw.close(); } private static void solve() throws IOException { n = nextInt(); a = nextInt(); b = nextInt(); k = nextInt(); c = next().toCharArray(); if (b == 1) { int ans = n - k - a + 1, cur = 0; pw.println(ans); for (int i = 0; i < n; ++i) { if (c[i] == '0') { pw.print((i + 1) + " "); ++cur; } if (cur == ans) break; } } else { int count = 0, c0 = 0; for (int i = 0; i < n; ++i) { if (c[i] == '0') ++c0; else { count += c0 / b; c0 = 0; } } count += c0 / b; int ans = count - a + 1, cur = 0; c0 = 0; pw.println(ans); for (int i = 0; i < n; ++i) { if (c[i] == '0') { ++c0; } else c0 = 0; if (c0 == b) { pw.print((i + 1) + " "); c0 = 0; cur++; } if (cur == ans) break; } } } private static int sumf(int[] fen, int id) { int summ = 0; for (; id >= 0; id = (id & (id + 1)) - 1) summ += fen[id]; return summ; } private static void addf(int[] fen, int id) { for (; id < fen.length; id |= id + 1) fen[id]++; } 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
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
f229f7e5ed404a73ccf760591619cf2c
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class b { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int k = in.nextInt(); String str = in.next(); char[] arr = str.toCharArray(); int amt = 0; int x = 0; int left = arr.length; for(int i = arr.length - 1; i >= 0; i--) { if(arr[i] == '1') { amt = 0; continue; } amt++; if(amt == b) { x++; amt = 0; left = i; if(x == a) { left = i; break; } } } ArrayList<Integer> ans = new ArrayList<>(); for(int i = 0; i < arr.length; i++) { if(i == left) { ans.add(i + 1); break; } if(arr[i] == '1') { amt = 0; continue; } amt++; if(amt == b) { ans.add(i + 1); amt = 0; } } out.println(ans.size()); for(int xx : ans) out.print(xx + " "); out.println(); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public long nextLong() throws IOException { return Long.parseLong(next()); } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for(int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for(int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } public int[] nextOffsetIntArray(int n) throws IOException { int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = nextInt() - 1; return arr; } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
e31d5c5bf1bdf20311d543c9f687c883
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.PriorityBlockingQueue; public class B { InputStream is; int __t__ = 1; int __f__ = 0; int __FILE_DEBUG_FLAG__ = __f__; String __DEBUG_FILE_NAME__ = "src/T"; FastScanner in; PrintWriter out; class State implements Comparable<State> { int len; int left; State(int len, int left) { this.len = len; this.left = left; } public int compareTo(State s) { return s.len - len; } public String toString() { return "(" + len + ", " + left + ")"; } } public void solve() { int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(), k = in.nextInt(); String s = in.next(); ArrayList<State> lens = new ArrayList<State>(); int ptr = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '1') { if (i - ptr != 0) lens.add(new State(i - ptr, ptr)); ptr = i + 1; } } if (s.length() - ptr != 0) lens.add(new State(s.length() - ptr, ptr)); Collections.sort(lens); int total = 0; for (int i = 0; i < lens.size(); i++) { total += lens.get(i).len / b; } ArrayList<Integer> res = new ArrayList<>(); main : for (int i = 0; i < lens.size() && total >= a; i++) { State next = lens.get(i); while (next.len >= b) { res.add(next.left + b); next.left += b; next.len -= b; total--; if (total < a) break; } } // System.out.println(Arrays.toString(lens.toArray(new State[0]))); out.println(res.size()); for (int i = 0; i < res.size(); i++) { out.print(res.get(i) + " "); } out.println(); out.close(); } public void run() { if (__FILE_DEBUG_FLAG__ == __t__) { try { is = new FileInputStream(__DEBUG_FILE_NAME__); } catch (FileNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } System.out.println("FILE_INPUT!"); } else { is = System.in; } in = new FastScanner(is); out = new PrintWriter(System.out); solve(); } public static void main(String[] args) { new B().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } 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; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { return nextIntArray(n, 0); } int[] nextIntArray(int n, int margin) { int[] array = new int[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextInt(); return array; } int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextIntArray(m); } return map; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { return nextLongArray(n, 0); } long[] nextLongArray(int n, int margin) { long[] array = new long[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextLong(); return array; } long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextLongArray(m); } return map; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { return nextDoubleArray(n, 0); } double[] nextDoubleArray(int n, int margin) { double[] array = new double[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextDouble(); return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextDoubleArray(m); } return map; } 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(); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
91a860569e3c0f0dc1bce6eb3db452a5
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.InputMismatchException; public class B { public static void main(String[] args) { FastScannerB sc = new FastScannerB(System.in); int N = sc.nextInt(); int A = sc.nextInt(); int B = sc.nextInt(); int K = sc.nextInt(); String st = sc.next(); st = st + "1"; //sentinel N++; ArrayList<Pair> emptyness = new ArrayList<>(); int currentLen = 0; int prev = -1; for(int i = 0; i<N; i++){ if(st.charAt(i) == '0'){ currentLen++; } else{ if(currentLen >= B) emptyness.add(new Pair(prev + 1, i)); currentLen = 0; prev = i; } } int totalShips = 0; for(Pair p : emptyness){ //System.out.println(p.left + " " + p.right); totalShips += (p.right - p.left) / B; } int toShoot = totalShips - A + 1; System.out.println(toShoot); StringBuilder sb = new StringBuilder(); for(int i = 0; i<toShoot; i++){ Pair current = emptyness.remove(0); current.right -= B; sb.append(current.right + 1); sb.append(' '); if(current.right - current.left >= B) emptyness.add(current); } System.out.println(sb); } } class Pair{ int left; int right; Pair(int l, int r){ left = l; right = r; } } class FastScannerB{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScannerB(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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(); } public String nextLine() { int c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isLineEndChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isLineEndChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
850def7e68f45d22b24972cb96dbc5db
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); // pw.println("Time used: " + (TIME_END - TIME_START) + "."); pw.close(); } public static class Task { public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int k = sc.nextInt(); char[] sots = sc.next().toCharArray(); List<Integer> hits = new ArrayList<>(); int numSpace = 0; for (int i = 0; i < sots.length; i++) { if (sots[i] == '0') { numSpace++; } else { numSpace = 0; } if (numSpace % b == 0 && numSpace != 0) { hits.add(i + 1); } } int pr = hits.size() - a + 1; pw.println(pr); for (int i = 0; i < pr; i++) { pw.print(hits.get(i) + " "); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
7959c66a738da9c3a80cef568d73694f
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
// package codeforces.other2017.technocup2017.round2.div1; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; public class B { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); in.nextInt(); char[] tried = in.nextToken().toCharArray(); List<int[]> spaces = new ArrayList<>(); int total = 0; int last = -1; for (int i = 0; i < n ; i++) { if (tried[i] == '1') { if (i-last > 1 && i-last-1 >= b) { spaces.add(new int[]{last+1, i-last-1}); total += (i-last-1)/b; } last = i; } } if (last != n-1 && n-last-1 >= b) { spaces.add(new int[]{last+1, n-last-1}); total += (n-last-1)/b; } int ans = 0; StringBuilder line = new StringBuilder(); for (int i = 0 ; i < spaces.size() ; i++) { int[] sp = spaces.get(i); while (total >= a && sp[1] >= b) { total--; ans++; line.append(' ').append(sp[0] + b); sp[1] -= b; sp[0] += b; } } out.println(ans); out.println(line.substring(1)); out.flush(); } 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; } private int[] nextInts(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } private int[][] nextIntTable(int n, int m) { int[][] ret = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextInt(); } } return ret; } private long[] nextLongs(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = nextLong(); } return ret; } private long[][] nextLongTable(int n, int m) { long[][] ret = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextLong(); } } return ret; } private double[] nextDoubles(int n) { double[] ret = new double[n]; for (int i = 0; i < n; i++) { ret[i] = nextDouble(); } return ret; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char) c; } if ('A' <= c && c <= 'Z') { return (char) c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { return Double.valueOf(nextToken()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
a2c42c2294d3d6c6874ff587ba3f08dc
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
//package tech2016.elim2; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), a = ni(), b = ni(), K = ni(); char[] s = ns(n); int[] lens = new int[n]; int p = 0; int pre = -1; for(int i = 0;i < n;i++){ if(s[i] == '1'){ if(i-pre > 1){ lens[p++] = i-pre-1; } pre = i; } } { int i = n; if(i-pre > 1){ lens[p++] = i-pre-1; } } lens = Arrays.copyOf(lens, p); int av = 0; for(int i = 0;i < p;i++){ av += lens[i]/b; } int ans = av - a + 1; out.println(ans); pre = -1; for(int i = 0;i < n;i++){ if(s[i] == '1'){ pre = i; }else{ if(i-pre == b && ans > 0){ out.print(i+1 + " "); pre = i; ans--; } } } out.println(); assert ans == 0; } 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]; private 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
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
f573846890f33a37c0832a066aace7ee
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; public class B implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static Random rnd = new Random(); private final static String fileName = ""; private static final char EMPTY = '1'; private void solve() { int n = readInt(); int shipsCount = readInt(); int shipLength = readInt(); int shootsCount = readInt(); char[] field = (readString() + EMPTY).toCharArray(); List<Integer> positions = getPositions(n, shipsCount, shipLength, shootsCount, field); out.println(positions.size()); for (int position : positions) { out.print((position + 1) + " "); } out.println(); } private static class Segment implements Comparable<Segment> { int from, to; int length; int minCount, maxCount; public Segment(int from, int to) { this.from = from; this.to = to; this.length = (to - from); } @Override public int compareTo(Segment other) { int delta = maxCount - minCount; int otherDelta = other.maxCount - other.minCount; return delta - otherDelta; } } private List<Integer> getPositions(int n, int shipsCount, int shipLength, int shootsCount, char[] field) { List<Segment> segments = new ArrayList<>(); int lastEmpty = -1; for (int i = 0; i <= n; ++i) { if (field[i] == EMPTY) { segments.add(new Segment(lastEmpty + 1, i)); lastEmpty = i; } } int totalCanShips = 0; for (Segment segment : segments) { totalCanShips += segment.length / shipLength; } for (Segment segment : segments) { int segmentCanShips = segment.length / shipLength; segment.maxCount = segmentCanShips; segment.minCount = Math.max(shipsCount - (totalCanShips - segmentCanShips), 0); } List<Integer> positions = new ArrayList<>(); PriorityQueue<Segment> queue = new PriorityQueue<>(); for (Segment segment : segments) { if (segment.maxCount == 0) continue; queue.add(segment); } while (true) { Segment first = queue.poll(); positions.add(first.from + shipLength - 1); first.from += shipLength; first.length -= shipLength; first.maxCount--; totalCanShips--; if (first.maxCount > 0) { queue.add(first); } if (totalCanShips < shipsCount) { break; } } return positions; } ///////////////////////////////////////////////////////////////////// private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = true; ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new B(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine()); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return result; throw new NumberFormatException(); } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } int getRealIndex() { return index + 1; } } private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants and functions //////////////// ///////////////////////////////////////////////////////////////////// private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } private static boolean checkBit(long mask, int bit){ return (mask & (1L << bit)) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private static class MultiSet<ValueType> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> multiset = new HashMap<>(); return new MultiSet<>(multiset); } private final Map<ValueType, Integer> multiset; private int size; public MultiSet(Map<ValueType, Integer> multiset) { this.multiset = multiset; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = get(value); multiset.put(value, count + 1); ++size; } public void dec(ValueType value) { int count = get(value); if (count == 0) return; if (count == 1) multiset.remove(value); else multiset.put(value, count - 1); --size; } public int get(ValueType value) { Integer count = multiset.get(value); return (count == null ? 0 : count); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int getId(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
3339ae34619f961d04452e8ebecb34b1
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class B { public void run() throws FileNotFoundException { //Scanner sc = new Scanner(new File("B.txt")); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String l = sc.nextLine(); int lastPos = -1; int total = 0; for (int i = 0; i < n; i++) { if (l.charAt(i) == '1') { total += (i - lastPos - 1) / b; lastPos = i; } } total += (n - lastPos - 1) / b; int hits = total - a + 1; System.out.println(hits); lastPos = -1; for (int i = 0; i < n; i++) { if (l.charAt(i) == '1') { for (int pos = lastPos + b; pos < i; pos += b) { if (hits > 0) { hits--; System.out.print((pos + 1) + " "); } else { return; } } lastPos = i; } } for (int pos = lastPos + b; pos < n; pos += b) { if (hits > 0) { hits--; System.out.print((pos + 1) + " "); } else { return; } } } public static void main(String[] args) throws FileNotFoundException { new B().run(); } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
a390f14539f7b5f193fb48ee5bb5a327
train_003.jsonl
1479632700
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.
256 megabytes
import java.io.*; import java.util.*; public class B implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start(); new B().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } int lcm(int a, int b) { return a / gcd(a, b) * b; } class Segment implements Comparable<Segment> { int start, length; public Segment(int start, int length) { this.start = start; this.length = length; } @Override public int compareTo(Segment o) { return Integer.compare(length, o.length); } } private void solve() { int n = readInt(); int count = readInt(); int length = readInt(); int shots = readInt(); char[] s = readString().toCharArray(); List<Segment> segments = new ArrayList<>(); int curLength = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { if (curLength >= length) { segments.add(new Segment(i - curLength, curLength)); } curLength = 0; } else { curLength++; } } if (curLength >= length) { segments.add(new Segment(n - curLength, curLength)); } int maxCount = 0; for (Segment seg : segments) { maxCount += seg.length / length; } List<Integer> answer = new ArrayList<>(); PriorityQueue<Segment> q = new PriorityQueue<>(); q.addAll(segments); while (!q.isEmpty()) { Segment cur = q.poll(); answer.add(cur.start + length); maxCount--; if (maxCount < count) break; int newStart = cur.start + length; int newLength = cur.length - length; if (newLength >= length) { q.add(new Segment(newStart, newLength)); } } out.println(answer.size()); for (int pos : answer) { out.print(pos + " "); } } }
Java
["5 1 2 1\n00100", "13 3 2 3\n1000000010001"]
1 second
["2\n4 2", "2\n7 11"]
NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
d50bb59298e109b4ac5f808d24fef5a1
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
1,700
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
standard output
PASSED
46dea28d691f489eec379af25c241c19
train_003.jsonl
1346427000
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj.Help the Little Elephant to count the answers to all queries.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF221D extends PrintWriter { CF221D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF221D o = new CF221D(); o.main(); o.flush(); } int[] ft; void update(int i, int n, int a) { while (i < n) { ft[i] += a; i |= i + 1; } } int query(int i) { int a = 0; while (i >= 0) { a += ft[i]; i &= i + 1; i--; } return a; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) { int a = sc.nextInt(); if (a > n) a = 0; aa[i] = a; } int[] ia = new int[n + 1]; Arrays.fill(ia, -1); int[] ka = new int[n + 1]; int[] pp = new int[n]; int[] kk = new int[n]; for (int i = 0; i < n; i++) { int a = aa[i]; if (a > 0) { pp[i] = ia[a]; ia[a] = i; kk[i] = ka[a]++; } } int[] ll = new int[m]; int[] rr = new int[m]; int[] ans = new int[m]; Integer[] hh = new Integer[m]; for (int h = 0; h < m; h++) { ll[h] = sc.nextInt() - 1; rr[h] = sc.nextInt() - 1; hh[h] = h; } Arrays.sort(hh, (h1, h2) -> ll[h2] - ll[h1]); ft = new int[n]; for (int h = 0, h_, i = n - 1, j; i >= 0; i--) { int a = aa[i]; if (a > 0 && (j = ia[a]) >= i) { int k = kk[j] - kk[i]; if (k == a - 1) { // 0 // 1 update(j, n, 1); } else if (k == a) { // 0 1 // 1 -1 update(j, n, -2); update(pp[j], n, 1); } else if (k == a + 1) { // 0 1 -1 // 1 -1 0 update(j, n, 1); ia[a] = j = pp[j]; update(j, n, -2); update(pp[j], n, 1); } } while (h < m && ll[h_ = hh[h]] == i) { ans[h_] = query(rr[h_]); h++; } } for (int h = 0; h < m; h++) println(ans[h]); } }
Java
["7 2\n3 1 2 2 3 3 7\n1 7\n3 4"]
4 seconds
["3\n1"]
null
Java 11
standard input
[ "data structures" ]
5c92ede00232d6a22385be29ecd06ddd
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≤ lj ≤ rj ≤ n).
1,800
In m lines print m integers — the answers to the queries. The j-th line should contain the answer to the j-th query.
standard output
PASSED
152dec5781c5d71229681bf64780f792
train_003.jsonl
1423931400
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
256 megabytes
import java.util.Scanner; public class Main { public static class Node { private Node[] children = new Node[3]; private boolean isWord; public Node() { isWord = false; for (int i = 0; i < 3; i++) children[i] = null; } void add(String key, Node node) { int index; for (int i = 0; i < key.length(); i++) { index = key.charAt(i) - 'a'; if (node.children[index] == null) node.children[index] = new Node(); node = node.children[index]; } node.isWord = true; } boolean fas(String key, int i, int mistakes, Node node) { if (mistakes == 2 || node == null) return false; if (i < key.length()) { int elem = key.charAt(i) - 'a', mistake = 0; if (node.children[elem] == null) mistake++; return fas(key, i + 1, mistakes + (elem == 0 ? 0 : 1), node.children[0]) || fas(key, i + 1, mistakes + (elem == 1 ? 0 : 1), node.children[1]) || fas(key, i + 1, mistakes + (elem == 2 ? 0 : 1), node.children[2]); } return node.isWord && (mistakes == 1); } } public static void main(String args[]) { Node root = new Node(); Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); in.nextLine(); for (int i = 0; i < n; i++) { root.add(in.nextLine(), root); } for (int i = 0; i < m; ++i) { String nas = root.fas(in.nextLine(), 0, 0, root) ? "YES" : "NO"; System.out.println(nas); } } }
Java
["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"]
3 seconds
["YES\nNO\nNO"]
null
Java 8
standard input
[ "hashing", "string suffix structures", "data structures", "binary search", "strings" ]
146c856f8de005fe280e87f67833c063
The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.
2,000
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
standard output
PASSED
e9dedbcd35ce58a8d99125ae69b71922
train_003.jsonl
1423931400
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
256 megabytes
import java.util.*; import java.io.*; public class WattoMechanism { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] in = br.readLine().split(" "); int n = Integer.parseInt(in[0]); int m = Integer.parseInt(in[1]); Trie t = new Trie(); for(int i = 0; i < n; i++) t.add(br.readLine()); for(int i = 0; i < m; i++) out.println(t.ans(br.readLine())); out.flush(); } static class Trie { // adjust size of map for range of characters // along with index making Trie[] map; char letter; int end, numStrings; public Trie() { this('$', 0); } // root constructor public Trie(char ll, int ee) { letter = ll; end = ee; map = new Trie[3]; for(int i = 0 ; i < 3 ; i++) map[i] = null; } public Trie add(String s) { Trie root = this; for(int i = 0 ; i < s.length() ; i++) { int index = s.charAt(i) - 'a'; if(root.map[index] == null) root.map[index] = new Trie(s.charAt(i), 0); root = root.map[index]; } root.end++; return this; } public String ans(String s) { if(contains(s, false, 0, this)) return "YES"; return "NO"; } public boolean contains(String s, boolean skipped, int i, Trie root) { if(i == s.length() && !skipped) return false; if(i == s.length()) return root.end > 0; boolean res = false; int index = s.charAt(i) - 'a'; //try skipping if(!skipped) { for(int j = 0; j < 3; j++) { if(index == j) continue; if(root.map[j] != null) { res |= contains(s, true, i+1, root.map[j]); } } } //try not skipping if(root.map[index] != null) res |= contains(s, skipped, i+1, root.map[index]); return res; } } } /* 50 1 abaa acaa adaa aeaa afaa agaa ahaa aiaa ajaa akaa alaa amaa anaa aoaa apaa aqaa araa asaa ataa auaa avaa awaa axaa ayaa azaa baaa caaa daaa eaaa faaa gaaa haaa iaaa jaaa kaaa laaa maaa naaa oaaa paaa qaaa raaa saaa taaa uaaa vaaa waaa xaaa yaaa zaaa aaaa 25 1 baaa caaa daaa eaaa faaa gaaa haaa iaaa jaaa kaaa laaa maaa naaa oaaa paaa qaaa raaa saaa taaa uaaa vaaa waaa xaaa yaaa zaaa aaaa */
Java
["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"]
3 seconds
["YES\nNO\nNO"]
null
Java 8
standard input
[ "hashing", "string suffix structures", "data structures", "binary search", "strings" ]
146c856f8de005fe280e87f67833c063
The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.
2,000
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
standard output