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
564e35e3228d595391005ec3ca84bbe5
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class B { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } catch (NullPointerException e) { line=null; } } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } 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 static void main(String [] argv) { //String filePath="input.txt"; //String filePath="D:\\_d\\learn\\coursera\\algorithms and design I\\data\\QuickSort.txt"; String filePath=null; if(argv.length>0)filePath=argv[0]; new B(filePath); } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } public B(String inputFile) { openInput(inputFile); readNextLine(); int n=NextInt(), m=NextInt(); boolean [] [] p = new boolean[n][m]; for(int i=0; i<n; i++) { readNextLine(); for(int j=0; j<m; j++) { p[i][j]=line.charAt(j)=='B'; } } boolean ret=true; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(!p[i][j])continue; for(int ii=0; ii<n; ii++) { for(int jj=0; jj<m; jj++) { if(!p[ii][jj])continue; boolean ok2=true; int x=i; int dx=1; if(x>ii)dx=-1; while(x!=ii) { x+=dx; if(!p[x][j])ok2=false; } x=j; if(x<jj)dx=1; else dx=-1; while(x!=jj) { x+=dx; if(!p[ii][x])ok2=false; } if(!ok2) { ok2=true; x=j; if(x<jj)dx=1; else dx=-1; while(x!=jj) { x+=dx; if(!p[i][x])ok2=false; } x=i; if(x<ii)dx=1; else dx=-1; while(x!=ii) { x+=dx; if(!p[x][jj])ok2=false; } } if(!ok2)ret=false; } } } } System.out.println(ret?"YES":"NO"); closeInput(); } public static void out(Object s) { try{ FileWriter fstream = new FileWriter("output.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write(s.toString()); out.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
bf84d8d9693aef20ca66b21240866345
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String [] sp = br.readLine().split(" "); int r = Integer.parseInt(sp[0]); int c = Integer.parseInt(sp[1]); char [][] inp = new char[r][c]; int [][] m = new int[r * c][2]; int x = 0; for (int i = 0; i < m.length; i++) { Arrays.fill(m[i], -1); } for (int i = 0; i < inp.length; i++) { inp[i] = br.readLine().toCharArray(); for (int j = 0; j < inp[0].length; j++) { if(inp[i][j] == 'B'){ m[x][0] = i; m[x++][1] = j; } } } boolean f = false; for (int i = 0; i < m.length; i++) { if(m[i][0] == -1) break; for (int j = i + 1; j < m.length; j++) { if(m[i][0] == m[j][0]){ for (int k = m[i][1]; k <= m[j][1]; k++) { if(inp[m[i][0]][k] == 'W'){ f = true; break; } } }else if(m[i][1] == m[j][1]){ for (int k = m[i][0]; k <= m[j][0]; k++) { if(inp[k][m[i][1]] == 'W'){ f = true; break; } } }else{ int a = m[i][0]; int b = m[j][1]; for (int k = m[i][1]; k <= b; k++) { if(inp[m[i][0]][k] == 'W'){ f = true; break; } } for (int k = a; k <= m[j][0]; k++) { if(inp[k][m[j][1]] == 'W'){ f = true; break; } } if(!f) continue; else{ boolean o = false; a = m[j][0]; b = m [i][1]; for (int k = b; k <= m[j][1]; k++) { if(inp[m[j][0]][k] == 'W'){ o = true; break; } } for (int k = m[i][0]; k <= a; k++) { if(inp[k][m[i][1]] == 'W'){ o = true; break; } } if(!o) f = false; } } if(f) break; } if(f) break; } if(f) System.out.println("NO"); else System.out.println("YES"); System.out.print(out); } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
0f0a9557ba7c2fed364463adace271d1
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.util.*; import java.util.regex.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.util.Collections.*; import java.io.*; public class _B { int di[] = { 0, 0, -1, 1 }; int dj[] = { -1, 1, 0, 0 }; void go(int i, int j) { for (int j2 = 0; j2 < 4; j2++) { int X = i + di[j2]; int Y = j + dj[j2]; if (X >= 0 && X < memo.length && Y >= 0 && Y < memo[X].length && !memo[X][Y] && grid[X][Y] == 'B') { memo[X][Y] = true; go(X, Y); } } } char[][] grid; boolean memo[][]; public void solve() { int N = readInt(); int M = readInt(); grid = new char[N][M]; for (int i = 0; i < N; i++) { grid[i] = in.next().toCharArray(); } boolean no = false; memo = new boolean[N][M]; int f = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (grid[i][j] == 'B' && !memo[i][j]) { if (f == 1) { System.out.println("NO"); return; } memo[i][j] = true; f++; go(i, j); } } } outer: for (int i = 0; i < M; i++) { int w = 0, b = 0; boolean blackfinished = false; for (int j = 0; j < N; j++) { if (grid[j][i] == 'W') { if (b > 0) blackfinished = true; w++; } if (grid[j][i] == 'B') { if (blackfinished) { no = true; break outer; } b++; } } } outer: for (int i = 0; i < N; i++) { int w = 0, b = 0; boolean blackfinished = false; for (int j = 0; j < M; j++) { if (grid[i][j] == 'W') { if (b > 0) blackfinished = true; w++; } if (grid[i][j] == 'B') { if (blackfinished) { no = true; break outer; } b++; } } } if (no) { System.out.println("NO"); return; } // node[] nn = new node[M]; ArrayList<node> nn = new ArrayList<_B.node>(); for (int i = 0; i < M; i++) { int a = Integer.MAX_VALUE, b = -1; for (int j = 0; j < N; j++) { if (grid[j][i] == 'B') { a = min(j, a); b = max(j, b); } } if(a!=Integer.MAX_VALUE) nn.add(new node(a, b)); } // print(nn); for (int i = 0; i < nn.size(); i++) { for (int j = i + 1; j < nn.size(); j++) { if (nn.get(i).a > nn.get(j).b) { System.out.println("NO"); return; } if (nn.get(i).b < nn.get(j).a) { System.out.println("NO"); return; } if (nn.get(i).b < nn.get(j).b && nn.get(i).a < nn.get(j).a) { System.out.println("NO"); return; } if (nn.get(i).b > nn.get(j).b && nn.get(i).a > nn.get(j).a) { System.out.println("NO"); return; } } } System.out.println("YES"); } class node { int a, b; public node(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return a+" "+b; } } _B() { in = new Scanner(System.in); out = new PrintWriter(System.out); } public static void close() { in.close(); out.close(); } public static void main(String[] args) throws Exception { new _B().solve(); close(); } static Scanner in; static PrintWriter out; static int readInt() { return in.nextInt(); // return parseInt(in.nextLine()); } static int[] readIntArray() { String l[] = in.nextLine().split(" "); int[] r = new int[l.length]; for (int i = 0; i < l.length; i++) { r[i] = parseInt(l[i]); } return r; } static void print(Object... ob) { System.out.println(Arrays.deepToString(ob).replace("],", "],\n")); } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
2879977a255b7feb0bf697d601547209
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.util.Scanner; public class Convex { public static void main (String[] args) { Scanner s = new Scanner(System.in); String line = s.nextLine(); Scanner linescan = new Scanner(line); int n = linescan.nextInt(); int m = linescan.nextInt(); char[][] grid = new char[n][m]; for (int i = 0; i < n; i++) { line = s.nextLine(); for (int j = 0; j < m; j++) { grid[i][j] = line.charAt(j); } } System.out.println(new Convex().isConvex(grid)); } public static char[][]copyGrid (char[][] grid) { char[][] grid2 = new char[grid.length][grid[0].length]; for (int i = 0; i < grid.length ; i++) for (int j = 0; j < grid[0].length; j++) grid2[i][j] = grid[i][j]; return grid2; } public boolean checkBlack(char[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 'B') return true; } } return false; } public String isConvex (char[][] grid) { int i = 0, j = 0; for (i = 0; i < grid.length ; i++ ) { for ( j = 0; j < grid[i].length; j++) { if (grid[i][j] == 'B') { char[][] testgrid = copyGrid(grid); traverse (testgrid, i, j, 1, '?'); if (checkBlack(testgrid)) return "NO"; } } } return "YES"; } public void traverse (char[][] grid, int i, int j, int maxturn, char lastDirection) { if (maxturn < 0) return; if (i < 0 || j < 0) return ; if (i >= grid.length) return; if (j >= grid[i].length) return; if (grid[i][j] =='W') return; if (grid[i][j] == 'B') grid[i][j] = 'V'; traverse(grid, i, j+1, lastDirection == 'e' || lastDirection == '?' ? maxturn: maxturn - 1, 'e'); traverse(grid, i, j-1, lastDirection == 'w' || lastDirection == '?'?maxturn : maxturn - 1, 'w'); traverse(grid, i-1, j, lastDirection == 'n' || lastDirection == '?'? maxturn: maxturn - 1, 'n'); traverse(grid, i+1, j, lastDirection == 's' || lastDirection == '?'? maxturn: maxturn - 1, 's'); } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
180ab7a3b48142b7e34d22b015c99687
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; /** * @author Ivan Pryvalov (ivan.pryvalov@gmail.com) */ public class Codeforces_R168_Div2_B implements Runnable{ char[][] c; int[][] used; int n,m; private void solve() throws IOException { n = scanner.nextInt(); //50 m = scanner.nextInt(); //50 c = new char[n][m]; for (int i = 0; i < c.length; i++) { c[i] = scanner.nextToken().toCharArray(); } int cntBlck = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cntBlck += c[i][j] == 'B' ? 1 : 0; } } boolean result = true; for (int i = 0; i < n && result; i++) { for (int j = 0; j < m; j++) { if (c[i][j]=='B'){ used = new int[n][m]; go(i,j, -1, 2); int curCnt = 0; for (int i2 = 0; i2 < n; i2++) { for (int j2 = 0; j2 < m; j2++) { curCnt += used[i2][j2]; } } if (curCnt != cntBlck){ result = false; break; } } } } out.println(result? "YES" : "NO"); } int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}; private void go(int i, int j, int dir, int left) { if (i<0 || i>=n || j<0 || j>=m || left<0) return; if (c[i][j] != 'B') return; if (used[i][j] == 0){ used[i][j] = 1; } for(int iDir=0; iDir<dirs.length; iDir++){ if (iDir==dir || left>0){ go(i+dirs[iDir][0], j+dirs[iDir][1], iDir, iDir==dir? left : left-1); } } } ///////////////////////////////////////////////// final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ; final int BUF_SIZE_INPUT = 1024; final int BUF_SIZE_OUT = 1024; boolean inputFromFile = false; String filenamePrefix = "A-small-attempt0"; String inSuffix = ".in"; String outSuffix = ".out"; PrintStream out; ByteScanner scanner; ByteWriter writer; public void run() { try{ InputStream bis = null; OutputStream bos = null; //PrintStream out = null; if (inputFromFile){ File baseFile = new File(getClass().getResource("/").getFile()); bis = new BufferedInputStream( new FileInputStream(new File( baseFile, filenamePrefix+inSuffix)), INPUT_BUFFER_SIZE); bos = new BufferedOutputStream( new FileOutputStream( new File(baseFile, filenamePrefix+outSuffix))); out = new PrintStream(bos); }else{ bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE); bos = new BufferedOutputStream(System.out); out = new PrintStream(bos); } scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE); writer = new ByteWriter(bos, BUF_SIZE_OUT); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } public interface Constants{ final static byte ZERO = '0';//48 or 0x30 final static byte NINE = '9'; final static byte SPACEBAR = ' '; //32 or 0x20 final static byte MINUS = '-'; //45 or 0x2d final static char FLOAT_POINT = '.'; } public static class EofException extends IOException{ } public static class ByteWriter implements Constants { int bufSize = 1024; byte[] byteBuf = new byte[bufSize]; OutputStream os; public ByteWriter(OutputStream os, int bufSize){ this.os = os; this.bufSize = bufSize; } public void writeInt(int num) throws IOException{ int byteWriteOffset = byteBuf.length; if (num==0){ byteBuf[--byteWriteOffset] = ZERO; }else{ int numAbs = Math.abs(num); while (numAbs>0){ byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO); numAbs /= 10; } if (num<0) byteBuf[--byteWriteOffset] = MINUS; } os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset); } /** * Please ensure ar.length <= byteBuf.length! * * @param ar * @throws IOException */ public void writeByteAr(byte[] ar) throws IOException{ for (int i = 0; i < ar.length; i++) { byteBuf[i] = ar[i]; } os.write(byteBuf,0,ar.length); } public void writeSpaceBar() throws IOException{ byteBuf[0] = SPACEBAR; os.write(byteBuf,0,1); } } public static class ByteScanner implements Constants{ InputStream is; public ByteScanner(InputStream is, int bufSizeInput, int bufSize){ this.is = is; this.bufSizeInput = bufSizeInput; this.bufSize = bufSize; byteBufInput = new byte[this.bufSizeInput]; byteBuf = new byte[this.bufSize]; } public ByteScanner(byte[] data){ byteBufInput = data; bufSizeInput = data.length; bufSize = data.length; byteBuf = new byte[bufSize]; byteRead = data.length; bytePos = 0; } private int bufSizeInput; private int bufSize; byte[] byteBufInput; byte by=-1; int byteRead=-1; int bytePos=-1; byte[] byteBuf; int totalBytes; boolean eofMet = false; private byte nextByte() throws IOException{ if (bytePos<0 || bytePos>=byteRead){ byteRead = is==null? -1: is.read(byteBufInput); bytePos=0; if (byteRead<0){ byteBufInput[bytePos]=-1;//!!! if (eofMet) throw new EofException(); eofMet = true; } } return byteBufInput[bytePos++]; } /** * Returns next meaningful character as a byte.<br> * * @return * @throws IOException */ public byte nextChar() throws IOException{ while ((by=nextByte())<=0x20); return by; } /** * Returns next meaningful character OR space as a byte.<br> * * @return * @throws IOException */ public byte nextCharOrSpacebar() throws IOException{ while ((by=nextByte())<0x20); return by; } /** * Reads line. * * @return * @throws IOException */ public String nextLine() throws IOException { readToken((byte)0x20); return new String(byteBuf,0,totalBytes); } public byte[] nextLineAsArray() throws IOException { readToken((byte)0x20); byte[] out = new byte[totalBytes]; System.arraycopy(byteBuf, 0, out, 0, totalBytes); return out; } /** * Reads token. Spacebar is separator char. * * @return * @throws IOException */ public String nextToken() throws IOException { readToken((byte)0x21); return new String(byteBuf,0,totalBytes); } /** * Spacebar is included as separator char * * @throws IOException */ private void readToken() throws IOException { readToken((byte)0x21); } private void readToken(byte acceptFrom) throws IOException { totalBytes = 0; while ((by=nextByte())<acceptFrom); byteBuf[totalBytes++] = by; while ((by=nextByte())>=acceptFrom){ byteBuf[totalBytes++] = by; } } public int nextInt() throws IOException{ readToken(); int num=0, i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } public long nextLong() throws IOException{ readToken(); long num=0; int i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i<totalBytes; i++){ num*=10; num+=byteBuf[i]-ZERO; } return sign?-num:num; } /* //TODO test Unix/Windows formats public void toNextLine() throws IOException{ while ((ch=nextChar())!='\n'); } */ public double nextDouble() throws IOException{ readToken(); char[] token = new char[totalBytes]; for (int i = 0; i < totalBytes; i++) { token[i] = (char)byteBuf[i]; } return Double.parseDouble(new String(token)); } public int[] loadIntArray(int size) throws IOException{ int[] a = new int[size]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] loadLongArray(int size) throws IOException{ long[] a = new long[size]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } } public static abstract class Timing{ private static int counter = 0; protected String name = "Timing"+(++counter); private boolean debug; public Timing(boolean debug) { super(); this.debug = debug; } public abstract void run(); public void start(){ long time1 = System.currentTimeMillis(); run(); long time2 = System.currentTimeMillis(); if (debug) System.out.println(name+" time = "+(time2-time1)/1000.0+" ms."); } } public static class Alg{ public static interface BooleanChecker{ public boolean check(long arg); } public static class BinarySearch{ /** * This check returns boolean value, result of function. * It should be monotonic. * * @return */ public BooleanChecker bc; /** * Returns following element: <pre> 0 0 [1] 1 1</pre> */ public long search(long left, long right){ while (left<=right){ long mid = (left+right)/2; if (bc.check(mid)){ right = mid-1; }else{ left = mid+1; } } return left; } /** * Optional.<br> * Returns following element: <pre> 1 1 [1] 0 0</pre> */ public long searchInverted(long left, long right){ while (left<=right){ long mid = (left+right)/2; if (!bc.check(mid)){ right = mid-1; }else{ left = mid+1; } } return left - 1; } } } public static class Modulo{ long mod = (long)1e9+7; public Modulo(long mod) { super(); this.mod = mod; } public long inv(int a) { long res = pow(a, mod-2); return res; } public long pow(long a, long x) { if (x==0) return 1; long part = 1; if ((x&1)!=0) part = a; return (part * pow((a*a)%mod, x>>1)) % mod; } } public static void main(String[] args) { new Codeforces_R168_Div2_B().run(); } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
eb865d56a01b50c3bfec0234b49dc6f4
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.awt.Point; import java.math.BigInteger; import static java.lang.Math.*; public class Codeforces_Solutions implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new Codeforces_Solutions(), "", 128 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } class Point { int x; int y; public Point(int x, int y) { this.x=x; this.y=y; } } boolean DEBUG = false; ArrayList<Point> a; char[][] board = new char[50][50]; void solve() throws IOException{ a = new ArrayList<Point>(); int n = readInt(); int m = readInt(); //in.readLine(); for (int i=0; i<n; i++) { String s = in.readLine(); for (int j=0; j<m; j++) { if (s.charAt(j)=='B') a.add(new Point(i,j)); board[i][j] = s.charAt(j); } } for (int i=0; i<a.size(); i++) for (int j=0; j<a.size(); j++) { if (i==j) continue; int x = a.get(i).x; int y = a.get(i).y; int xx = a.get(j).x; int yy = a.get(j).y; boolean f = true; if (x<xx) { for (int k=x; k<=xx; k++) if (board[k][y]=='W') f=false; } else { for (int k=xx; k<=x; k++) if (board[k][y]=='W') f=false; } if (y<yy) { for (int k=y; k<=yy; k++) if (board[xx][k]=='W') f=false; } else { for (int k=yy; k<=y; k++) if (board[xx][k]=='W') f=false; } boolean ff = true; if (y<yy) { for (int k=y; k<=yy; k++) if (board[x][k]=='W') ff=false; } else { for (int k=yy; k<=y; k++) if (board[x][k]=='W') ff=false; } if (x<xx) { for (int k=x; k<=xx; k++) if (board[k][yy]=='W') ff=false; } else { for (int k=xx; k<=x; k++) if (board[k][yy]=='W') ff=false; } if (!f && !ff) { out.print("NO"); return; } } out.print("YES"); } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
ba2c3572eeec0bea8b4f8cf1be30c261
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B275 { /** * @param args */ public static void main(String[] args)throws IOException,FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in )); String line = in.readLine(); StringTokenizer st = new StringTokenizer (line); int n= Integer.parseInt(st.nextToken()); int m= Integer.parseInt(st.nextToken()); int g[][] = new int[n+1][m+1]; int used[][] = new int[n+1][m+1]; int mas[] = new int[100]; int d[] = new int[100]; for (int i = 0; i < n; i++){ line = in.readLine(); for (int j = 0; j < m; j++) { if (line.charAt(j)=='B') g[i][j] = 1; else g[i][j] = 0; } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) for (int x = 0; x < n; x++) for (int y = 0; y < m; y++){ if ((g[i][j]==1) && (g[x][y]==1)) if (!check(g,i,j,x,y)) { /* System.out.println(i); System.out.println(j); System.out.println(x); System.out.println(y); */ System.out.print("NO"); return; } } System.out.print("YES"); } static boolean check(int[][] a, int x1, int y1, int x2, int y2) { if (x1 > x2) { int s = x1; x1 = x2; x2 = s; s = y1; y1 = y2; y2 = s; } boolean ok = true; for (int i = x1; i <= x2; i++) { if (a[i][y1] == 0) { ok = false; } } if (ok) { for (int i = y1; i <= y2; i++) { if (a[x2][i] == 0) { ok = false; } } return ok; } ok = true; for (int i = y1; i <= y2; i++) { if (a[x1][i] == 0) { ok = false; } } if (ok) { for (int i = x1; i <= x2; i++) { if (a[i][y2] == 0) { ok = false; } } return ok; } return false; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
488bc96b59105d0d8b6a2c10dc416445
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.util.*; public class Main { static char[][] grid; static boolean[][] area; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); grid = new char[n][m]; area = new boolean[n][m]; for (int i = 0; i < n; i++) { grid[i] = sc.next().toCharArray(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { area[i][j] = grid[i][j] == 'B'; } } System.out.println(solve(n, m) ? "YES" : "NO"); } static boolean solve(int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!area[i][j]) continue; for (int k = i; k < n; k++) { for (int l = 0; l < m; l++) { if (!area[k][l]) continue; boolean flag1 = true; boolean flag2 = true; if (j > l) { for (int a = j; a >= l; a--) { flag1 &= area[i][a]; flag2 &= area[k][a]; } for (int a = i; a <= k; a++) { flag1 &= area[a][l]; flag2 &= area[a][j]; } } else { for (int a = j; a <= l; a++) { flag1 &= area[i][a]; flag2 &= area[k][a]; } for (int a = i; a <= k; a++) { flag1 &= area[a][l]; flag2 &= area[a][j]; } } if (!flag1 && !flag2) return false; } } } } return true; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
e0d2f07c917767b8f564bb4f2566950f
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.TreeMap; public class B { static final int MAX = 3000000; static int[] ary = new int[MAX]; static int[][] field; static int[][] field0; static boolean[][] bfield; static final int[][] DIR = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int LEFT = 0; static final int RIGHT = 1; static final int UP = 2; static final int DOWN = 3; static int n, m; public static void main(String[] args) { doIt(); } static void doIt() { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); field = new int[n][m]; field0 = new int[n][m]; int black = 0; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { if(s.charAt(j) == 'W') {field[i][j] = -1;field0[i][j] = MAX;} else {field[i][j] = 0;field0[i][j] = 2;black++;} } } boolean bb = true; for (int i = 0; i < n; i++) { if(!bb) break; for (int j = 0; j < m; j++) { if(field0[i][j] == 2) { bfield = new boolean[n][m]; search(i, j, 1, -1); for (int j2 = 0; j2 < n; j2++) { for (int k = 0; k < m; k++) { if(field0[j2][k] == 2 && bfield[j2][k] == false){ bb = false; break; } } } } } } if(bb) System.out.println("YES"); else System.out.println("NO"); } static void search(int i, int j, int v, int d){ if(0 <= i && i < n && 0<=j && j<m && field[i][j] >= 0 && 0 <= v){ //System.out.println("i = " + i + ", j = " + j + ", v = " + v + ", d = " + d); //field[i][j] += 1; bfield[i][j] = true; for (int j2 = 0; j2 < DIR.length; j2++) { if(d == j2 || d == -1) search(i+DIR[j2][0], j+DIR[j2][1], v, j2); else search(i+DIR[j2][0], j+DIR[j2][1], v - 1, j2); } } } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
4302e5987ef58d9e42143ba66f6c635d
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Integer.*; import static java.lang.System.out; import static java.lang.Math.*; public class Main { static boolean[][] grid; static boolean[][] seen; static int m,n; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] inp = in.readLine().trim().split("\\s+"); n = parseInt(inp[0]); m = parseInt(inp[1]); grid = new boolean[n][m]; for (int i = 0; i < n; i++) { String line = in.readLine().trim(); for (int j = 0; j < m;j++) { grid[i][j] = line.charAt(j)=='B'; } } boolean flag = false; outer: for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!grid[i][j]) continue; seen = new boolean[n][m]; int p = n-1; //for (; p < n; p++) for (;p>=i+1;p--) for (int q = m-1; q >=0; q--) { if (!grid[p][q]) continue; if (seen[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } p = i; for (int q = m-1; q >=j+1; q--) { if (!grid[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } } } out.println(flag?"NO":"YES"); } public static boolean check(int ii, int jj, int p, int q) { boolean res = true; int i = ii, j = jj; boolean xdir = (p-i)>0, ydir = (q-j)>0; //go on x direction first while (i!=p) { res = grid[i][j]; if (!res) break; seen[i][j] = true; i += (xdir)?1:-1; } if (res) { while (j!=q) { res = grid[p][j]; if (!res) break; seen[i][j] = true; j += (ydir)?1:-1; } } if (res) return !res; res = true; i = ii; j = jj; //go on y direction first while (j!=q) { res = grid[i][j]; if (!res) break; seen[i][j] = true; j += (ydir)?1:-1; } if (res) { while (i!=p) { res = grid[i][q]; if (!res) break; seen[i][j] = true; i += (xdir)?1:-1; } } return !res; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
bf865a47a4decb0bd3c8d64ad4a467ef
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Integer.*; import static java.lang.System.out; import static java.lang.Math.*; public class Main { static boolean[][] grid; static int m,n; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] inp = in.readLine().trim().split("\\s+"); n = parseInt(inp[0]); m = parseInt(inp[1]); grid = new boolean[n][m]; for (int i = 0; i < n; i++) { String line = in.readLine().trim(); for (int j = 0; j < m;j++) { grid[i][j] = line.charAt(j)=='B'; } } boolean flag = false; outer: for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!grid[i][j]) continue; int p = n-1; //for (; p < n; p++) for (;p>=i+1;p--) for (int q = m-1; q >=0; q--) { if (!grid[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } p = i; for (int q = m-1; q >=j+1; q--) { if (!grid[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } } } out.println(flag?"NO":"YES"); } public static boolean check(int ii, int jj, int p, int q) { boolean res = true; int i = ii, j = jj; boolean xdir = (p-i)>0, ydir = (q-j)>0; //go on x direction first while (i!=p) { res = grid[i][j]; if (!res) break; i += (xdir)?1:-1; } if (res) { while (j!=q) { res = grid[p][j]; if (!res) break; j += (ydir)?1:-1; } } if (res) return !res; res = true; i = ii; j = jj; //go on y direction first while (j!=q) { res = grid[i][j]; if (!res) break; j += (ydir)?1:-1; } if (res) { while (i!=p) { res = grid[i][q]; if (!res) break; i += (xdir)?1:-1; } } return !res; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
1402caca82c0c18749ad39da9a90e510
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Integer.*; import static java.lang.System.out; import static java.lang.Math.*; public class Main { static boolean[][] grid; static int m,n; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] inp = in.readLine().trim().split("\\s+"); n = parseInt(inp[0]); m = parseInt(inp[1]); grid = new boolean[n][m]; for (int i = 0; i < n; i++) { String line = in.readLine().trim(); for (int j = 0; j < m;j++) { grid[i][j] = line.charAt(j)=='B'; } } boolean flag = false; outer: for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!grid[i][j]) continue; int p = i; for (int q = j+1; q <m; q++) { if (!grid[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } for (p = i+1 ; p < n; p++) { for (int q = 0; q <m; q++) { if (!grid[p][q]) continue; if (flag = check(i,j,p,q)) break outer; } } } } out.println(flag?"NO":"YES"); } public static boolean check(int ii, int jj, int p, int q) { boolean res = true; int i = ii, j = jj; boolean xdir = (p-i)>0, ydir = (q-j)>0; //go on x direction first while (i!=p) { res = grid[i][j]; if (!res) break; i += (xdir)?1:-1; } if (res) { while (j!=q) { res = grid[p][j]; if (!res) break; j += (ydir)?1:-1; } } if (res) return !res; res = true; i = ii; j = jj; //go on y direction first while (j!=q) { res = grid[i][j]; if (!res) break; j += (ydir)?1:-1; } if (res) { while (i!=p) { res = grid[i][q]; if (!res) break; i += (xdir)?1:-1; } } return !res; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
bf9974c15efebb72e2b99a8f9fdf79fb
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { static boolean[][] black; static int[][] b; 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()), m = Integer.parseInt(st.nextToken()); black = new boolean[n][m]; b = new int[n*m][2]; int cnt = 0; for (int i = 0; i < n; i++) { String s = br.readLine(); for (int j = 0; j < s.length(); j++) if (s.charAt(j) == 'B'){ black[i][j] = true; b[cnt][0] = i; b[cnt++][1] = j; } } boolean ok = true; for(int i = 0; i < cnt && ok; i++) for(int j = i+1; j < cnt && ok; j++) if(!can(i, j)) ok = false; System.out.println(ok ? "YES" : "NO"); } private static boolean can(int i, int j) { int i1 = b[i][0], j1 = b[i][1]; int i2 = b[j][0], j2 = b[j][1]; boolean ok1 = true; if(i1 < i2){ for(int k = i1; k <= i2 && ok1; k++) if(!black[k][j1]) ok1 = false; for(int k = Math.min(j1, j2); k <= Math.max(j1, j2) && ok1; k++) if(!black[i2][k]) ok1 = false; }else{ for(int k = i2; k <= i1 && ok1; k++) if(!black[k][j1]) ok1 = false; for(int k = Math.min(j1, j2); k <= Math.max(j1, j2) && ok1; k++) if(!black[i2][k]) ok1 = false; } boolean ok2 = true; if(i1 < i2){ for(int k = i1; k <= i2 && ok2; k++) if(!black[k][j2]) ok2 = false; for(int k = Math.min(j1, j2); k <= Math.max(j1, j2) && ok2; k++) if(!black[i1][k]) ok2 = false; }else{ for(int k = i2; k <= i1 && ok2; k++) if(!black[k][j2]) ok2 = false; for(int k = Math.min(j1, j2); k <= Math.max(j1, j2) && ok2; k++) if(!black[i1][k]) ok2 = false; } return ok1 | ok2; } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
c6de12ff5e3b46a694be9b6d3a9a5d48
train_001.jsonl
1361374200
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
256 megabytes
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class B { static int[][] ch; static int a; static int b; public static void main(String[] args) { Scanner in = new Scanner(System.in); a = in.nextInt(); b = in.nextInt(); char[][] map = new char[a][b]; for (int i = 0; i < a; i++) { String t = in.next(); for (int j = 0; j < b; j++) { map[i][j] = t.charAt(j); } } boolean ans = true; stop: for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { if (map[i][j] == 'B') { ch = new int[a][b]; for (int ii = 0; ii < a; ii++) { for (int jj = 0; jj < b; jj++) { if (map[ii][jj] == 'W') { ch[ii][jj] = 1; } } } ch[i][j] = -1; dfs(i, j, 2, 0); for (int ii = 0; ii < a; ii++) { for (int jj = 0; jj < b; jj++) { if (ch[ii][jj] == 0) { ans = false; break stop; } } } } } } if (ans) { System.out.println("YES"); } else { System.out.println("NO"); } } static void dfs(int i, int j, int p, int dir) { if (0 < i && ch[i - 1][j] != 1) { if (dir == 1) { ch[i - 1][j] = -1; dfs(i - 1, j, p, 1); } else if (p > 0) { ch[i - 1][j] = -1; dfs(i - 1, j, p - 1, 1); } } if (0 < j && ch[i][j - 1] != 1) { if (dir == 2) { ch[i][j - 1] = -1; dfs(i, j - 1, p, 2); } else if (p > 0) { ch[i][j - 1] = -1; dfs(i, j - 1, p - 1, 2); } } if (i < a - 1 && ch[i + 1][j] != 1) { if (dir == 3) { ch[i + 1][j] = -1; dfs(i + 1, j, p, 3); } else if (p > 0) { ch[i + 1][j] = -1; dfs(i + 1, j, p - 1, 3); } } if (j < b - 1 && ch[i][j + 1] != 1) { if (dir == 4) { ch[i][j + 1] = -1; dfs(i, j + 1, p, 4); } else if (p > 0) { ch[i][j + 1] = -1; dfs(i, j + 1, p - 1, 4); } } } }
Java
["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"]
2 seconds
["NO", "YES"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
3631eba1b28fae473cf438bc2f0552b7
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.
1,700
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
standard output
PASSED
c09eda87a0df1dc21a2f17bde5bb4bb9
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Abc{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int bef[]=new int[n]; int aft[]=new int[n]; for (int i=0;i<n;i++){ bef[i]=sc.nextInt(); aft[i]=sc.nextInt(); } // Arrays.sort(bef); // Arrays.sort(aft); boolean rated=false; boolean maybe=true; for (int i=0;i<n;i++){ if (bef[i]!=aft[i]){ rated=true; break; } if (i>0 && bef[i-1]<bef[i]){ maybe=false; } } if (rated){ System.out.println("rated"); }else if (maybe){ System.out.println("maybe"); }else { System.out.println("unrated"); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
cb3058769462aab230b9ec809cd576db
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
/** * @author uglypish * Problem: Is It Rated? * Description: Code forces has conducted another challenge round. Two participants will be compared by their scores if it is rated, unrated or impossible to rate. The scores will be known from top to bottom of their standings. */ import java.util.Scanner; public class Rated { public static void main(String[] args) { Rated r = new Rated(); r.rate(); } public void rate(){ Scanner in = new Scanner(System.in); String[] str_score = new String[2]; String score; int s1=0, s2=0; int rounds = in.nextInt(); int[] m1 = new int[rounds]; int[] m2 = new int[rounds]; in.nextLine(); for(int i=0; i < rounds; i++) { score = in.nextLine(); str_score = score.split(" "); m1[i] = Integer.valueOf(str_score[0]); m2[i] = Integer.valueOf(str_score[1]); s1 += m1[i]; s2 += m2[i]; } if(s1 > s2 || s2 > s1) { System.out.println("rated"); }else if(s1 == s2) { int y=0, w=0; for(int x=0; x < rounds-1; x++) { if(m1[x] >= m1[x+1] && m2[x] >= m2[x+1]) { y++; }else { w++; } } if(w>0) { for(int a=0; a < rounds; a++) { if(!(m1[a] == m2[a])) { System.out.println("rated"); break; }else { System.out.println("unrated"); break; } } }else { for(int b=0; b < rounds; b++) { if(!(m1[b] == m2[b])) { System.out.println("rated"); break; }else { System.out.println("maybe"); break; } } } } in.close(); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
ccd9980c1221dd2ffba6a27bc97cb28d
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
public class Main { public static void main(String[] args) { java.util.Scanner sc = new java.util.Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); b[i] = sc.nextInt(); } for (int i = 0; i < n; i++) if (a[i] != b[i]) { System.out.println("rated"); System.exit(0); } for (int i = 0; i < n-1; i++) if(a[i]<a[i+1]) { System.out.println("unrated"); System.exit(0); } System.out.println("maybe"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
21bb6d6243a145c40952312df8d611f8
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; public class Solution { static Scanner sc = new Scanner(System.in); public static void main(String args[]) { int size = sc.nextInt(); int pf = sc.nextInt(); int ps = sc.nextInt(); int c = 0; if (pf - ps != 0) { System.out.println("rated"); return; } for (int i = 1; i < size; i++) { int f = sc.nextInt(); int s = sc.nextInt(); if (f - s != 0) { System.out.println("rated"); return; } if (f - pf > 0) { c++; } pf = f; ps = s; } if (c > 0) { System.out.println("unrated"); }else System.out.println("maybe"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
8cc2e368ea8af4fb9bee96bb383fd0aa
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; public class CODE { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); int n1 = sc.nextInt(); int n2 = sc.nextInt(); boolean flag = false; for (int i = 1; i < n; i++) { if (n1 - n2 != 0) { System.out.println("rated"); return; } int now1 = sc.nextInt(); int now2 = sc.nextInt(); if (now1 > n1 || now2 > n2) { flag = true; } n1 = now1; n2 = now2; } if (n1 - n2 != 0) { System.out.println("rated"); return; } if (flag) { System.out.println("unrated"); } else { System.out.println("maybe"); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
c0e5f314f81f3b2b1257f10fc0e5e7eb
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Scanner; import java.lang.Math; public class knk { public static void main(String[] args) { Scanner in = new Scanner(System.in) ; int n = in.nextInt() ; int [] a = new int[n] ; int [] b = new int[n] ; for(int i = 0 ;i<n;i++) { a[i] = in.nextInt() ; b[i] = in.nextInt() ; if(a[i] != b[i]) { System.out.println("rated"); return ; } } int flag=0 ; for(int i = 1 ;i<n;i++) { if(a[i-1] < a[i]) { flag=1 ; } if(flag==1 && i==n-1) { System.out.println("unrated"); return ; } } System.out.println("maybe"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
011f2506ed330af7c44ef66d3322ae52
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.*; import java.util.*; public class Task { static final StdIn in = new StdIn(); static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // int t = in.nextInt(); int n = in.nextInt(); //rating notequals = rated //rating equals and rating order : if ordered nas is may be : else unrated boolean isRatingChanged = false; Rating[] rr = new Rating[n]; for (int i = 0; i < n; i++) { Rating r = new Rating(); r.before = in.nextInt(); r.after = in.nextInt(); rr[i] = r; if(r.before != r.after) { isRatingChanged = true; } } boolean isAsc = false; for (int i = 1; i < rr.length; i++) { if(isRatingChanged) { break; } if((rr[i].after <= rr[i-1].after)) { isAsc = true; } else { isAsc = false; break; } if((rr[i].before <= rr[i-1].before)) { isAsc = true; } else { isAsc = false; break; } } if(isRatingChanged) { out.println("rated"); } else if(isAsc) { out.println("maybe"); } else { out.println("unrated"); } out.println(); out.close(); } static class Rating { int before; int after; } static class Pair1 { long first; long second; } static void swap(int a, int b) { int temp = a; a = b; b = temp; } public static ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist) { // Arraylist for storing reversed elements // this.revArrayList = alist; for (int i = 0; i < alist.size() / 2; i++) { Integer temp = alist.get(i); alist.set(i, alist.get(alist.size() - i - 1)); alist.set(alist.size() - i - 1, temp); } // Return the reversed arraylist return alist; } static class Pair { int first = 1; int second = 2; } public void fibonacci(int N) { boolean arr[] = new boolean[N]; Arrays.fill(arr, false); arr[0] = true; if(N>1) arr[1] = true; Pair p = new Pair(); for (int i = 3; i <= N; i++) { if(p.first + p.second == i) { arr[i-1] = true; p.first = p.second; p.second = i; } else { arr[i-1] = false; } } } public class Solver { Solver() { } } static long factorial(long x) { if(x <= 1) { return 1; } long res = 2; for (int i = 3; i <= x; i++) { res = res * i; } return res; } static long gcdOfFactorial(long a, long b) { if (b == 0) return a; return gcdOfFactorial(b, a % b); } static class StdIn { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(InputStream in) { try{ din = new DataInputStream(in); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public int[] readIntArray(int n, int os) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt()+os; return ar; } public long nextLong() { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long[] readLongArray(int n, long os) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong()+os; return ar; } public double nextDouble() { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
80f5404f5faabea06526b9023bf44f73
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.*; import java.util.*; public class Isitrated { public static void main(String[]args) { Scanner sc = new Scanner(System.in); int counter = 0; int n = sc.nextInt(); PrintWriter r = new PrintWriter(System.out); int []a = new int[n*2]; int i =0; int j =0; String s =""; while(n > j){ int x = sc.nextInt(); int y = sc.nextInt(); a[i] = x; a[i+1] = y; i = i+2; j++; if(x != y){ s = "rated"; } } for(i =0; i < n*2 & s!="rated" ;i++){ for(j =0 ;j < n*2;j++){ if( j > i){ if(i% 2== 0 & j % 2== 0){ if(a[i] <a[j]){ s = "unrated"; } } } } } if(s != "rated" & s!= "unrated"){ s = "maybe"; } r.println(s); r.flush(); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
c2b97b601edd45cc68036c6cf8afa7cb
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int[] befor, after; static int n; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tk; String line = null; n = Integer.parseInt(in.readLine()); befor = new int[n]; after = new int[n]; for (int i = 0; i < n; i++) { line = in.readLine(); String values[] = line.split(" "); befor[i] = Integer.parseInt(values[0]); after[i] = Integer.parseInt(values[1]); } calculate(); } static void calculate() { for (int i = 0; i < n; i++) { if (befor[i] != after[i]) { System.out.println("rated"); return; } } for (int i = 0; i < n; i++) { if (isThereMax(i)) { System.out.println("unrated"); return; } } System.out.println("maybe"); } public static int getIndexIfExist(int i) { for (int j = 0; j < n; j++) { if (j == i) { continue; } if (befor[i] == befor[j]) { return j; } } return -1; } static public boolean isThereMax(int i) { for (int j = i + 1; j < n; j++) { if (befor[i] < befor[j]) return true; } return false; } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
c106c4eec2ba4a879a1d6d7d2f90c632
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.*; import java.util.*; public class Problems1 { public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(System.in); int n=sc.nextInt(); int x,y; int p=1000000000; boolean f=false; for(int i=0;i<n;i++){ x=sc.nextInt(); y=sc.nextInt(); if(x!=y){ System.out.println("rated"); return; }else if(y>p){ f=true; } p=y; } if(f)System.out.println("unrated"); else System.out.println("maybe"); } public static void dis(int a[]){ StringBuilder s=new StringBuilder(); for(int i=0;i<a.length;i++){ s.append(a[i]+" "); } System.out.println(s.toString()); } //__________________________________________________________ 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 long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } //$ } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
bba421dde5624f71ee625cd97153e673
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class JavaApplication35 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); int [] c=new int [n]; int [] v=new int [n]; for(int i=0;i<n;i++){ c[i]=sc.nextInt(); v[i]=sc.nextInt(); } int j=0; int q=8; for(int i=0;i<n;i++){ if(c[i]!=v[i]){ j=1; q=1; break; } } Arrays.sort(c); for(int i=0;i<n;i++){ if(j==0){ if(c[n-i-1]==v[i]){ q=4; q++; } else{ q=0; break; } } } switch(q){ case 1: out.println("rated"); break; case 0: out.println("unrated"); break; default: out.println("maybe"); break; } out.println(" "); out.flush(); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
5d6fb8796732ab753fb80464f87cf829
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.*; import java.util.*; public class Problems1 { public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(System.in); int n=sc.nextInt(); int x,y; int p=1000000000; boolean f=false; for(int i=0;i<n;i++){ x=sc.nextInt(); y=sc.nextInt(); if(x!=y){ System.out.println("rated"); return; }else if(y>p){ f=true; } p=y; } if(f)System.out.println("unrated"); else System.out.println("maybe"); } public static void dis(int a[]){ StringBuilder s=new StringBuilder(); for(int i=0;i<a.length;i++){ s.append(a[i]+" "); } System.out.println(s.toString()); } //__________________________________________________________ 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 long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } //$ } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
9f6282cc9b50216777ca488e9ac58fc2
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class isitrated { // better solution for less steps public static int gcdFast(int x, int y) { if (y == 0) { return x; } else { return gcdFast(y, x % y); } } // public static int dfs(int node) { // visited[node] = true; // int c = 1; // for (int i : adjList[node]) { // if (!visited[i]) { // c += dfs(i); // } // } // return c; // Getting last occur of element // public static int binarySearch(int low, int n, int high) { // low = 0; // high = n - 1; // while (low <= high) { // int mid = (low + high) / 2; // if (x >= a[mid]) { // if (x == a[mid]) { // ans = mid; // } // low = mid + 1; // // } else if (a[mid] > x) { // high = mid - 1; // } // } // // } // Dynamic Window public static int smallestSubarray(int targetSum, int[] arr) { int minWindowSize = Integer.MAX_VALUE; int currentWindowSum = 0; int windowStart = 0; for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) { currentWindowSum += arr[windowEnd]; while (currentWindowSum >= targetSum) { minWindowSize = Math.min(minWindowSize, windowEnd - windowStart + 1); currentWindowSum -= arr[windowStart]; windowStart++; } } return minWindowSize; } /** * * Fixed Window Find the max sum subarray of a fixed size K * * Example input: [4, 2, 1, 7, 8, 1, 2, 8, 1, 0] * */ public static int findMaxSumSubarray(int[] arr, int k) { int maxValue = Integer.MIN_VALUE; int currentRunningSum = 0; for (int i = 0; i < arr.length; i++) { currentRunningSum += arr[i]; if (i >= k - 1) { maxValue = Math.max(maxValue, currentRunningSum); currentRunningSum -= arr[i - (k - 1)]; // Akher element fl 3 bto3 el K } } return maxValue; } public static int findLength(String str, int k) { int windowStart = 0, maxLength = -1; HashMap<Character, Integer> hs = new HashMap<Character, Integer>(); for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) { char rightChar = str.charAt(windowEnd); hs.put(rightChar, hs.getOrDefault(rightChar, 0) + 1); // Increasing its value by 1 and if it have no value // just its zero and add 1 while (hs.size() > k) { char leftChar = str.charAt(windowStart); hs.put(leftChar, hs.get(leftChar) - 1); if (hs.get(leftChar) == 0) { hs.remove(leftChar); } windowStart++; } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); } return maxLength; } public static class Pair implements Comparable<Pair> { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair A) { return this.a > A.a ? 1 : -1; // sorting ascending } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int max = 0; int temp = n; int x = 1; int d = 0; int c = 0; int r = 0; while (n-- > 0) { int a = sc.nextInt(); int b = sc.nextInt(); if (x == 1) { max = b; if (a == b) { c++; } else { r++; } } else if (max >= b) { d++; if (a == b) { c++; } else { r++; } max = b; } else if (b > max && a == b) { c++; } else if (b > max && a != b) { r++; } x = 0; } if (c == temp && d != temp - 1 && r == 0) { System.out.println("unrated"); } else if (r != 0) { System.out.println("rated"); } else { System.out.println("maybe"); } pw.flush(); pw.close(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextArr(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
0f092ec6dc94f00c5e612e2b03131e0b
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n + 1]; int[] b = new int[n + 1]; for(int i = 0; i < n; i++){ int a1 = sc.nextInt(); int b1 = sc.nextInt(); a[i] = a1; b[i] = b1; } sc.close(); for(int i = 0; i < n; i++){ if(a[i] != b[i]){ System.out.print("rated"); return; } } for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ if(a[j] < a[i]){ System.out.print("unrated"); return; } } } System.out.print("maybe"); return; } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
7bdf668b9fd39358bf89e2d0d058188f
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { int t = 1; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; int max = a[0]; String s ="maybe"; int min = 4126; for(int i = 0;i < n;i++) { a[i] = sc.nextInt(); b[i] = sc.nextInt(); if(a[i] != b[i]) { System.out.println("rated"); return; } } for(int i =1;i<n;i++) { if( a[i] > a[i-1]) { System.out.println("unrated"); return; } } System.out.println("maybe"); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready() || st.hasMoreTokens(); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
49481291f1dbce5c4391b971197c8377
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int x; x = scanner.nextInt(); boolean f = true, f1 = true; int[][] arr = new int[x][2]; int[] arr1 = new int[x]; for (int i = 0; i < x; ++i) { arr[i][0] = scanner.nextInt(); arr[i][1] = scanner.nextInt(); if (arr[i][0] != arr[i][1]) { f = false; break; } else { arr1[i] = arr[i][0]; } } if (f == false) { System.out.println("rated"); } else { Arrays.sort(arr1); int k = 0, j = x - 1; while (k < x) { if (arr[k][0] != arr1[j]) { f1 = false; break; } k++; j--; } if (f1 == false) { System.out.println("unrated"); } else { System.out.println("maybe"); } } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
97732fe2c65adc12f22dd46835ebf17c
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[] = new int[n]; Integer j[] = new Integer[n]; for(int i = 0 ; i < n; i++){ int f = in.nextInt(); int l = in.nextInt(); if(f!=l){System.out.println("rated");System.exit(0);} a[i] = f; j[i] = f; } Arrays.sort(j,Collections.reverseOrder()); boolean x = false; for(int i = 0 ; i <n ;i++){ // System.out.println("a[i] = "+a[i]+" "+"j[i] = "+j[i]); x = a[i]==j[i]; if(x==false) break; // System.out.println(x); } if(x== true) System.out.println("maybe"); else System.out.println("unrated"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
023695ae29e9388c646d3826e265cdbf
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; public class apples{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int i=0; int x=1; double temp=99e80; boolean flag=true; boolean car=true; boolean cops=true; while(n!=0) { int a=sc.nextInt(); int b=sc.nextInt(); if(a==b) { flag=true; if (a<=temp) { car=false; } else { cops=false; } } else { flag=false; break; } n=n-1; temp=a; } if (flag==false) System.out.println("rated"); else if (car==false && cops==true) System.out.println("maybe"); else if (cops==false) System.out.println("unrated"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
de257170bcd2603b14b4fa7956bebd4c
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
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.Arrays; import java.util.Collections; import java.util.Scanner; //import java.io.Reader; //import java.math.BigDecimal; //import java.util.ArrayList; //import java.util.Arrays; //ArrayList<Integer> list = new ArrayList<Integer>(); //import java.util.Collections; //import java.util.Scanner; import java.util.StringTokenizer; //import java.io.IOException; //import java.io.InputStream; //import java.io.InputStreamReader; import java.util.StringTokenizer; public class Div3 { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); boolean f1=true; int temp=Integer.MAX_VALUE; boolean f2=true; boolean f3=true; while(n!=0) { int a=sc.nextInt(); int b=sc.nextInt(); if(a>b || b>a) { f1=false; break; } else if(a==b) { if(temp>=a) { f2=true; } else { f3=false; } } temp=a; n--; } if(!f1) { System.out.println("rated"); } else if(f2 && f3) { System.out.println("maybe"); } else { System.out.println("unrated"); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public long[] nextLongArr(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } 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
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
1af82feb82c7c6daafbcb8cfbd4a1685
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Scanner; public class isit { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int []y=new int[n*2]; for(int i=0;i<y.length;i++){ y[i]=sc.nextInt(); } int c=0; boolean flag=true; for(int i=0;i<y.length-2;i+=2){ if(y[i]!=y[i+1]) c++; if(y[i]>=y[i+2]) ; else flag=false; } if(y[y.length-1]!=y[y.length-2]) c++; if(c==0 && flag==true) System.out.println("maybe"); else if(c==0 && flag==false) System.out.println("unrated"); else System.out.println("rated"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
6b9b228c62fb04fc99180ebf4ac057f7
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); int n=fs.nextInt(); int flag=0; int[] a = new int[n]; int[] b = new int[n]; for(int i=0;i<n;i++){ a[i]=fs.nextInt(); b[i]=fs.nextInt(); if(a[i] != b[i]) { out.println("rated"); out.close(); return; } if(i>=1 && a[i]>a[i-1] && flag == 0) flag=1; } if(flag == 1) { out.println("unrated"); out.close(); return; } out.println("maybe"); out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
f8db5280b78e67575293278b8277ceec
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastScanner fs=new FastScanner(); int n=fs.nextInt(); int flag=0; int[] a = new int[n]; int[] b = new int[n]; for(int i=0;i<n;i++){ a[i]=fs.nextInt(); b[i]=fs.nextInt(); if(a[i] != b[i]) { System.out.println("rated"+""); return; } if(i>=1 && a[i]>a[i-1] && flag == 0) flag=1; } if(flag == 1) { System.out.println("unrated"); return; } System.out.println("maybe"); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
5aae6f037fee997ec64c4c5a80bbdaae
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; public class rated { public static void main (String args[]) { Scanner a=new Scanner(System.in); int x=a.nextInt(); boolean f=false; boolean g=true; int [] []y=new int [x][2]; for(int i=0;i<x;i++) for(int j=0;j<2;j++) y[i][j]=a.nextInt(); for(int k=0;k<x;k++) { for(int l=0;l<1;l++) { if(y[k][0]!=y[k][1]) { f=true; g=false;} } if(f) { System.out.println("rated"); break; } } for(int m=0;m<x-1&&!f;m++) { if(y[m][0]<y[m+1][0]) { System.out.println("unrated"); g=false; break; } } if(g){ System.out.println("maybe"); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
da966d433d2b2c7301fcf22c0b8ac60a
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.*; import java.io.*; import java.io.IOException; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.io.BufferedReader; public class Rated { public static void main(String[] args) { IsRated(); } public static void IsRated(){ Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int[][] scores = new int[x][2];int i =0; while(i<x) { scores[i][0]=sc.nextInt(); scores[i][1]=sc.nextInt(); i++;} for(int j =0;j<scores.length;j++) { if(scores[j][0]!=scores[j][1]) {System.out.println("rated") ;return;}} for(int j =0;j<scores.length;j++) { for(int z=j;z<scores.length;z++) if((scores[j][0]<scores[z][0])) {System.out.println("unrated");return;} } System.out.println("maybe"); }}
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
8e34230ccab5c278049fc8665e5163f3
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
import java.util.Scanner; public class aaaa { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] x= new int[2][n]; for(int j=0;j<n;j++) { for(int i=0;i<2;i++) { x[i][j] = sc.nextInt(); } } boolean r =false; boolean m =true; for(int j=0;j<n;j++) { for(int i=0;i<1;i++) { if(!(x[i][j]==x[i+1][j])) { r=true; } } } for(int j=0;j<n-1;j++) { for(int i=0;i<1;i++) { if(x[i][j]<x[i][j+1]) { m=false; } } } if(r) { System.out.println("rated"); } else if (m) { System.out.println("maybe"); } else { System.out.println("unrated"); } } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
b45f6b7b712ef075b05ea48c113d78e6
train_001.jsonl
1494171900
Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
256 megabytes
//author: Ala Abid import java.io.*; import java.util.*; public class A { 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()); char ans='m'; int pa,pb; st = new StringTokenizer(br.readLine()); int a=Integer.parseInt(st.nextToken()); int b =Integer.parseInt(st.nextToken()); pa=a; pb=b; boolean test=false; if (a!=b) { ans='r';test=true; } for(int i=1;i<n;i++){ st = new StringTokenizer(br.readLine()); a=Integer.parseInt(st.nextToken()); b =Integer.parseInt(st.nextToken()); if(test==false){ if (a!=b) { ans='r';test=true; } else if (pb<b) ans='u'; } pa=a;pb=b; } if(ans=='r')System.out.println("rated"); else if(ans=='u')System.out.println("unrated"); else System.out.println("maybe"); } }
Java
["6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884", "4\n1500 1500\n1300 1300\n1200 1200\n1400 1400", "5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699"]
2 seconds
["rated", "unrated", "maybe"]
NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.
Java 8
standard input
[ "implementation", "sortings" ]
88686e870bd3bfbf45a9b6b19e5ec68a
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
900
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
standard output
PASSED
d9cc87ad88e8e6bdf2b17464baecac7e
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.*; import java.util.*; public class main { public static String getParity(long n){ String l="000000000000000000"; int c=17; while(c>=0){ long p=n%10; if(p%2==1){ if(c==17){ l=l.substring(0,17)+"1"; } else if(c==0){ l="1"+l.substring(0); } else l=l.substring(0,c)+"1"+l.substring(c+1); } n/=10; c--; } return l; } public static void main(String[] args) { InputReader sc=new InputReader(System.in); int n=sc.nextInt(); //System.out.println(); HashMap<String,Integer> map=new HashMap<String,Integer>(); for(int i=0;i<n;i++){ String str=sc.nextLine(); String sp[]=str.split(" "); if(str.charAt(0)=='+'){ String par=getParity(Long.parseLong(sp[1])); // System.out.println(par); if(map.containsKey(par)){ map.replace(par,map.get(par)+1); } else map.put(par, 1); } if(str.charAt(0)=='-'){ String par=getParity(Long.parseLong(sp[1])); //System.out.println(par); if(map.get(par)!=1){ map.replace(par,map.get(par)-1); } else map.remove(par); } if(str.charAt(0)=='?'){ long ans=0; String par=getParity(Long.parseLong(sp[1])); //System.out.println(par); if(map.containsKey(par)){ // System.out.println(""); ans+=map.get(par); } System.out.println(ans); } /*if(str.charAt(0)=='?'){ long ans=0; Iterator it=map.entrySet().iterator(); while(it.hasNext()){ int c=0; Map.Entry pair = (Map.Entry)it.next(); long k = (long) pair.getKey(); int v = (int) pair.getValue(); int x=sp[1].length()-1; if(k==0 && sp[1].charAt(0)==0){ ans+=v; } else{ while(k>0 || x>=0){ //System.out.println(k); long p=k%10; int z=0; if(x<0) z=0; else z=(int)sp[1].charAt(x)-48; if(p%2!=z){ c=1; //System.out.println("in"); break; } k=k/10; x--; } if(c==0) ans+=v; } } System.out.println(ans); }*/ } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
0d8660c4ef42cd0414b97b26aa952c94
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.TreeMap; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int Q = in.nextInt(); CountMap<String> map = new CountMap<>(); while (Q-- > 0) { String type = in.next(); if (type.equals("+")) { long v = in.nextLong(); map.inc(getSignature(v)); } else if (type.equals("-")) { long v = in.nextLong(); map.dec(getSignature(v)); } else { String p = pad(new StringBuilder(in.next())).toString(); int cnt = map.get(p); out.println(Math.max(0, cnt)); } } } private String getSignature(long num) { StringBuilder s = new StringBuilder(""); while (num > 0) { int d = (int) (num % 10); if (d % 2 == 0) { s.insert(0, "0"); } else { s.insert(0, "1"); } num /= 10; } return pad(s).toString(); } private StringBuilder pad(StringBuilder s) { while (s.length() < 18) { s.insert(0, "0"); } return s; } } static class CountMap<K> { public TreeMap<K, Integer> internalMap; public CountMap() { internalMap = new TreeMap<>(); } public Integer inc(K key) { Integer count = internalMap.get(key); count = (count == null) ? 1 : count + 1; internalMap.put(key, count); return count; } public Integer dec(K key) { Integer count = internalMap.get(key); count = (count == null) ? -1 : count - 1; internalMap.put(key, count); return count; } public Integer get(K key) { Integer cnt = internalMap.get(key); return cnt == null ? 0 : cnt; } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
e74bb93157e8226a26c2251af580dc4a
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int Q = in.nextInt(); CountHashMap<String> map = new CountHashMap<>(); while (Q-- > 0) { String type = in.next(); if (type.equals("+")) { long v = in.nextLong(); map.inc(getSignature(v)); } else if (type.equals("-")) { long v = in.nextLong(); map.dec(getSignature(v)); } else { String p = pad(new StringBuilder(in.next())).toString(); int cnt = map.get(p); out.println(Math.max(0, cnt)); } } } private String getSignature(long num) { StringBuilder s = new StringBuilder(""); while (num > 0) { int d = (int) (num % 10); if (d % 2 == 0) { s.insert(0, "0"); } else { s.insert(0, "1"); } num /= 10; } return pad(s).toString(); } private StringBuilder pad(StringBuilder s) { while (s.length() < 18) { s.insert(0, "0"); } return s; } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class CountHashMap<K> { public HashMap<K, Integer> internalMap; public CountHashMap() { internalMap = new HashMap<>(); } public Integer inc(K key) { Integer count = internalMap.get(key); count = (count == null) ? 1 : count + 1; internalMap.put(key, count); return count; } public Integer dec(K key) { Integer count = internalMap.get(key); count = (count == null) ? -1 : count - 1; internalMap.put(key, count); return count; } public Integer get(K key) { Integer cnt = internalMap.get(key); return cnt == null ? 0 : cnt; } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
dfb7f7a8352a773951eb032200a272a8
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/** * Created by mo on 9/14/16. */ import java.io.*; import java.util.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int[] freqs = new int[1 << 18]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++){ char type = sc.next().charAt(0); String num = sc.next(); if (type == '+'){ int pattern = numToPattern(num); freqs[pattern]++; } else if (type == '-'){ int pattern = numToPattern(num); freqs[pattern]--; } else { int pattern = Integer.parseInt(num, 2); sb.append(freqs[pattern]).append('\n'); } } System.out.println(sb); } private static int numToPattern(String num) { int pattern = 0; for (int i = 0; i < num.length(); i++){ int digit = num.charAt(num.length() - i - 1) - '0'; if (digit % 2 == 1){ pattern |= (1 << i); } } return pattern; } 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
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
2174be07d222a09d3c9f00f21e1e2c5e
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class SonyaandQueries { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); HashMap<String, Integer> m = new HashMap<>(); ArrayList<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < t; i++) { String q = br.readLine(); String[] qParts = q.split(" "); String type = qParts[0]; String value = qParts[1]; String pattern = getPattern(value); if (type.equals("+") || type.equals("-")) { if (type.equals("+")) { m.put(pattern, m.getOrDefault(pattern, 0) + 1); } else { m.put(pattern, m.get(pattern) - 1); } } else { res.add(m.containsKey(pattern)? m.get(pattern): 0); } } res.forEach(e -> System.out.println(e)); } public static String getPattern(String value) { StringBuilder sb = new StringBuilder(); int i = 0; while (i < value.length() && (int)(value.charAt(i) - '0') % 2 == 0) { i++; } for (; i < value.length(); i++) { if ((int)(value.charAt(i) - '0') % 2 == 0) { sb.append("0"); } else { sb.append("1"); } } return sb.toString().length() == 0? "0" : sb.toString(); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
a7cdc095afe7ed60244d5f7ac31d8c61
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C { //IO static BufferedReader f; static PrintWriter out; static StringTokenizer st; final public static void main( String[] args ) throws IOException { f = new BufferedReader( new InputStreamReader( System.in ) ); out = new PrintWriter( System.out ); solve(); f.close(); out.close(); System.exit( 0 ); } static final int MAXS = (2 << 18) - 1; static int[] counts = new int[MAXS + 1]; static int getIdx(long n) { int rtn = 0; int pow = 1; long rem = n; while (rem > 0) { long digit = rem % 10; if (digit % 2 != 0) { rtn += pow; } rem /= 10; pow <<= 1; } return rtn; } final public static void solve() throws IOException { int t = nextInt(); for (int i = 0; i < t; ++i) { String op = nextToken(); long val = nextLong(); if (op.equals("+")) { ++counts[getIdx(val)]; } else if (op.equals("-")) { --counts[getIdx(val)]; } else { System.out.println(counts[getIdx(val)]); } } } final public static String nextToken() throws IOException { while ( st == null || !st.hasMoreTokens() ) { st = new StringTokenizer( f.readLine() ); } return st.nextToken(); } final public static int nextInt() throws IOException { return Integer.parseInt( nextToken() ); } final public static long nextLong() throws IOException { return Long.parseLong( nextToken() ); } final public static double nextDouble() throws IOException { return Double.parseDouble( nextToken() ); } final public static boolean nextBoolean() throws IOException { return Boolean.parseBoolean( nextToken() ); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
b86bd12b226307b7503b2c02a89d0cac
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Swatantra */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int t = in.nextInt(); HashMap<Long, Integer> h = new HashMap<>(); while (t > 0) { String c = in.next(); String v = in.next(); int i; if (c.equals("+") || c.equals("-")) { StringBuilder s = new StringBuilder(); for (i = 0; i < v.length(); i++) { int val = (v.charAt(i) - '0') % 2; //System.out.println("Value is="+val); s.append(val); } //System.out.println("end"); long index = Long.parseLong(s.toString()); if (c.equals("+")) { if (h.containsKey(index)) { int prev = h.get(index); h.put(index, prev + 1); } else { h.put(index, 1); } } else { //System.out.println("del "+index); int prev = h.get(index); h.put(index, prev - 1); } } else { long index = Long.parseLong(v); if (h.get(index) != null) out.println(h.get(index)); else out.println(0); } t--; } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
56bcba021aadd9f74e513f414794c31d
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; /** * Created by Akshay on 12/4/17. */ public class Week_8_Codeforces_C { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); HashMap<String, Integer> map = new HashMap<>(); StringBuilder out = new StringBuilder(); for(int i = 0; i < t; i++){ st = new StringTokenizer(br.readLine()); String s = st.nextToken(); if(s.equals("+")){ Long num = Long.parseLong(st.nextToken()); StringBuilder sb = new StringBuilder(); while(num > 0){ long x = num % 10; if(x % 2 == 0){ sb.append('0'); } else{ sb.append('1'); } num /= 10; } sb.reverse(); String res = sb.toString(); res = res.replaceFirst("^0+(?!$)", ""); if(map.containsKey(res)){ map.put(res, map.get(res) + 1); } else{ map.put(res, 1); } } if(s.equals("-")){ Long num = Long.parseLong(st.nextToken()); StringBuilder sb = new StringBuilder(); while(num > 0){ long x = num % 10; if(x % 2 == 0){ sb.append('0'); } else{ sb.append('1'); } num /= 10; } sb.reverse(); String res = sb.toString(); res = res.replaceFirst("^0+(?!$)", ""); map.put(res, map.get(res) - 1); } if(s.equals("?")){ String str = st.nextToken(); str = str.replaceFirst("^0+(?!$)", ""); if(map.containsKey(str)) { out.append(map.get(str)); } else{ out.append(0); } out.append("\n"); } } System.out.println(out.toString()); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
3b8320f6d4e8ee8fc1415560d6e5964d
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
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 { private int transform(String v) { char arr[] = v.toCharArray(); int ans = 0; for (int i = 0; i < arr.length; i++) { int temp = arr[i] - '0'; ans = ans * 2 + (temp % 2); } return ans; } private int getPatternScore(String v) { char arr[] = v.toCharArray(); int ans = 0; for (int i = 0; i < arr.length; i++) { int temp = arr[i] - '0'; ans = ans * 2 + temp; } return ans; } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); int arr[] = new int[(int) 1e6]; for (int i = 0; i < t; i++) { char x = in.nextChar(); String v = in.next(); if (x == '+') { arr[transform(v)]++; } else if (x == '-') { arr[transform(v)]--; } else { out.println(arr[getPatternScore(v)]); } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
db979257cc2119587b13faf248ca77de
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/* * Remember a 6.0 student can know more than a 10.0 student. * Grades don't determine intelligence, they test obedience. * I Never Give Up. * I will become Candidate Master. * I will defeat Saurabh Anand. * Skills are Cheap,Passion is Priceless. */ import java.util.*; import java.util.Map.Entry; import java.io.*; import static java.lang.System.out; import static java.util.Arrays.*; import static java.lang.Math.*; public class ContestMain { private static Reader in=new Reader(); private static StringBuilder ans=new StringBuilder(); private static long MOD=1000000000+7;//10^9+7 private static final int N=100000+7; //10^5+7 // private static final double EPS=1e-9; // private static final int LIM=26; // private static final double PI=3.1415; private static ArrayList<Integer> v[]=new ArrayList[N]; // private static int color[]=new int[N]; private static boolean mark[]=new boolean[N]; // private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // private static ArrayList<Pair> v[]=new ArrayList[N]; private static long powmod(long x,long n){ if(n==0||x==0)return 1; else if(n%2==0)return(powmod((x*x)%MOD,n/2)); else return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD; } private static void shuffle(long [] arr) { for (int i = arr.length - 1; i >= 2; i--) { int x = new Random().nextInt(i - 1); long temp = arr[x]; arr[x] = arr[i]; arr[i] = temp; } } // private static long gcd(long a, long b){ // if(b==0)return a; // return gcd(b,a%b); // } // private static boolean check(int x,int y){ // if((x>=0&&x<n)&&(y>=0&&y<m)&&mat[x][y]!='X'&&!visited[x][y])return true; // return false; // } // static class Node{ // int left; // int right; // Node(){ // left=0; // right=0; // } // } public static void main(String[] args) throws IOException{ int t=in.nextInt(); HashMap<String,Integer> strmap=new HashMap(); char com; String pat; long num; long mod; String numpat,substr; int last_one; while(t-->0){ com=in.next().charAt(0); if(com=='?'){ pat=new StringBuilder(in.next()).reverse().toString(); if(!strmap.containsKey(pat))ans.append(0+"\n"); else ans.append(strmap.get(pat)+"\n"); } else if(com=='+'){ numpat=""; num=in.nextLong(); for(long i=num;i!=0;i/=10){ mod=i%10; if(mod%2==0)numpat+="0"; else numpat+="1"; } last_one=-1; for(int i=0;i<numpat.length();i++){ if(numpat.charAt(i)=='1')last_one=i; } if(!strmap.containsKey(numpat))strmap.put(numpat,1); else strmap.put(numpat,strmap.get(numpat)+1); substr=numpat.substring(0,last_one+1); if(!substr.equals(numpat)){ if(!strmap.containsKey(substr))strmap.put(substr,1); else strmap.put(substr,strmap.get(substr)+1); } int len=substr.length(); int i=last_one+1; while(true){ if(i>=numpat.length())substr+="0"; else substr=numpat.substring(0,i+1); if(substr.length()>19)break; // out.println(substr); if(!substr.equals(numpat)){ if(!strmap.containsKey(substr))strmap.put(substr,1); else strmap.put(substr,strmap.get(substr)+1); } i++; } } else{ numpat=""; num=in.nextLong(); for(long i=num;i!=0;i/=10){ mod=i%10; if(mod%2==0)numpat+="0"; else numpat+="1"; } substr=""; last_one=-1; for(int i=0;i<numpat.length();i++){ if(numpat.charAt(i)=='1')last_one=i; } strmap.put(numpat,strmap.get(numpat)-1); substr=numpat.substring(0,last_one+1); if(!numpat.equals(substr))strmap.put(substr,strmap.get(substr)-1); int len=substr.length(); int i=last_one+1; while(true){ if(i>=numpat.length())substr+="0"; else substr=numpat.substring(0,i+1); if(substr.length()>19)break; if(!substr.equals(numpat))strmap.put(substr,strmap.get(substr)-1); i++; } } } out.println(ans); } static class Pair<T> implements Comparable<Pair>{ int l; int r; int ind; Pair(){ l=0; r=0; ind=0; } Pair(int k,int v,int i){ l=k; r=v; ind=i; } // @Override // public int compareTo(Pair o) { // if(o.l!=l)return (int) (l-o.l); // else return (int)(r-o.r); // } //Fenwick tree question comparator @Override public int compareTo(Pair o) { if(o.r!=r)return (int) (r-o.r); else return (int)(l-o.l); } } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { 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
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
6958c9e31eb5acffb5ee9ae2224de845
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); HashMap<String, Integer> hm = new HashMap<>(); while (t-- > 0) { String q = scan.next(); if (q.equals("+")) { String s = scan.next(); char[] a = new char[19]; for (int i = 0; i < 19; i++) { if (i < s.length()) a[18 - i] = ((int) s.charAt(s.length() - 1 - i) - '0') % 2 == 0 ? '0' : '1'; else a[18 - i] = '0'; } s = ""; for (int i = 0; i < 19; i++) s += a[i]; if (hm.containsKey(s)) hm.put(s, hm.get(s) + 1); else hm.put(s, 1); } else if (q.equals("-")) { String s = scan.next(); char[] a = new char[19]; for (int i = 0; i < 19; i++) { if (i < s.length()) a[18 - i] = ((int) s.charAt(s.length() - 1 - i) - '0') % 2 == 0 ? '0' : '1'; else a[18 - i] = '0'; } s = ""; for (int i = 0; i < 19; i++) s += a[i]; hm.put(s, hm.get(s) - 1); } else { String s = scan.next(); char[] a = new char[19]; for (int i = 0; i < 19; i++) { if (i < s.length()) a[18 - i] = ((int) s.charAt(s.length() - 1 - i) - '0') % 2 == 0 ? '0' : '1'; else a[18 - i] = '0'; } s = ""; for (int i = 0; i < 19; i++) s += a[i]; if (hm.containsKey(s)) System.out.println(hm.get(s)); else System.out.println(0); // System.out.println(hm.containsKey(s) ? hm.get(s) : 0); } } scan.close(); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
bbbd963d465ec72509da848e21d06633
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
//package CodeForces.Round371; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C714 { public static void main(String[] args) { sc sc = new sc(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); HashMap<Long, Integer> v = new HashMap<>(); HashMap<String, Integer> l = new HashMap<>(); for (int i = 0; i < n; i++) { char s = sc.next().charAt(0); if (s == '+') { long a = sc.nextLong(); StringBuilder sb = new StringBuilder(); for (long j = a; j > 0; j/=10) { if (j%2 == 0) sb.insert(0,'0'); else sb.insert(0,'1'); } if (a == 0) sb.append('0'); if (v.containsKey(a)) v.put(a, v.get(a)+1); else v.put(a, 1); String st = sb.toString(); if (l.containsKey(st)) l.put(st, l.get(st) + 1); else l.put(st, 1); } else if (s == '-') { long a = sc.nextLong(); StringBuilder sb = new StringBuilder(); for (long j = a; j > 0; j/=10) { if (j%2 == 0) sb.insert(0,'0'); else sb.insert(0,'1'); } if (a == 0) sb.append('0'); if (v.get(a) > 1) v.put(a, v.get(a)-1); else v.remove(a); String st = sb.toString(); if (l.get(st) > 1) l.put(st, l.get(st) - 1); else l.remove(st); } else { String s1 = sc.next(); int ans = 0; if (s1.indexOf('1') >= 0) s1 = s1.substring(s1.indexOf('1')); else s1 = ""; for (; s1.length() <= 18 ; s1='0'+s1) { if (l.containsKey(s1)) ans+= l.get(s1); } out.println(ans); } } out.close(); } public static class sc { BufferedReader br; StringTokenizer st; public sc() { 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(); } Integer 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
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
43419505f55b3ab4e1a4d2ce29d1b6af
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static Random rnd = new Random(); boolean checkIndex(int index, int size) { return (0 <= index && index < size); } String shablon(long a) { int[] k = new int[20]; for (int i = 0; i < 20; i++) { if ((a % 10) % 2 == 0) { k[i] = 0; } else { k[i] = 1; } a /= 10; } String ans = ""; for (int i = 0; i < 20; i++) { ans += k[i]; } return ans; } // ====================================================== void solve() throws IOException { int t = rI(); HashMap<Long, Integer> map1 = new HashMap<Long, Integer>(); HashMap<String, Integer> map2 = new HashMap<String, Integer>(); for (int i = 0; i < t; i++) { char[] a = rS().toCharArray(); if (a[0] == '+') { long b = rL(); String c = shablon(b); map1.put(b, map1.getOrDefault(b, 0) + 1); map2.put(c, map2.getOrDefault(c, 0) + 1); } if (a[0] == '-') { long b = rL(); String c = shablon(b); if (map1.get(b) == 1) { map1.remove(b); } else { map1.put(b, map1.get(b) - 1); } if (map2.get(c) == 1) { map2.remove(c); } else { map2.put(c, map2.get(c) - 1); } } if (a[0] == '?') { char[] s = rS().toCharArray(); String ans = ""; for (int g = 0; g < s.length; g++) { ans = s[g] + ans; } while (ans.length() < 20) { ans += 0; } out.println(map2.getOrDefault(ans, 0)); } } } // =========================================================================== long min(long... values) { long min = Integer.MAX_VALUE; for (long value : values) { min = Math.min(min, value); } return min; } int max(int... values) { int max = Integer.MIN_VALUE; for (int value : values) { max = Math.max(max, value); } return max; } // ============================================================================== public static void main(String[] args) { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer tok; int maxA(int[] a) { int max = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { if (a[i] > max) { max = a[i]; } } return max; } int minA(int[] a) { int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) { if (a[i] < min) { min = a[i]; } } return min; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); } void run() { try { long timeStart = System.currentTimeMillis(); init(); solve(); out.close(); long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeStart) + " COMPILED"); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((-memoryTotal + memoryFree) >> 10) + " KB"); } String readLine() throws IOException { return in.readLine(); } String delimiter = " "; String rS() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(delimiter); } int[] rA(int b) { int a[] = new int[b]; for (int i = 0; i < b; i++) { try { a[i] = rI(); } catch (IOException e) { e.printStackTrace(); } } return a; } int rI() throws IOException { return Integer.parseInt(rS()); } long rL() throws IOException { return Long.parseLong(rS()); } void sort(int[] a) { Integer arr[] = new Integer[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = a[i]; } Arrays.sort(arr); for (int i = 0; i < a.length; i++) { a[i] = arr[i]; } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
6431c8e2c651d1fd4ad8df0895a7b61a
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class C371 { 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()); HashMap<Integer, Integer> l = new HashMap<Integer, Integer>(); C371 myC = new C371(); for (int i = 0; i < n ; i++) { st = new StringTokenizer(br.readLine()); String cur = st.nextToken(); String curl = st.nextToken(); if (cur.equals("+")) { StringBuilder sb = new StringBuilder(""); for (int j = 0; j < curl.length(); j++) { sb.append((curl.charAt(j) - '0') % 2); } //sb = myC.zero(sb); //System.out.println(sb.toString()); int t = Integer.parseInt(sb.toString(), 2); if (l.containsKey(t)) l.put(t, l.get(t)+1); else l.put(t, 1); } else if (cur.equals("-")) { StringBuilder sb = new StringBuilder(""); for (int j = 0; j < curl.length(); j++) { sb.append((curl.charAt(j) - '0') % 2); } // //sb = myC.zero(sb); //System.out.println(sb.toString()); int t = Integer.parseInt(sb.toString(), 2); l.put(t, l.get(t) - 1 ); } else { int count = 0; StringBuilder sb = new StringBuilder(""); for (int j = 0; j < curl.length(); j++) { sb.append((curl.charAt(j) - '0') % 2); } int t = Integer.parseInt(sb.toString(), 2); if (l.containsKey(t)) count = l.get(t); System.out.println(count); } } } public StringBuilder zero(StringBuilder sb) { int len = 17 - sb.length(); StringBuilder res = new StringBuilder(); for (int i = 0; i < len; i++) { res.append(0); } res.append(sb.toString()); //System.out.println(res.toString()); return res; } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
b93c26e3352a034517e4a11f3efc626f
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeMap; public class c { static class Trie { Trie[] child; int count; public Trie() { child = new Trie[2]; count = 0; } void add(String s) { Trie root = this; for (int i = s.length() - 1; i >= 0; i--) { int index = (s.charAt(i) - '0') % 2; if (root.child[index] == null) { root.child[index] = new Trie(); } root = root.child[index]; } for (int i = 0; i < 18 - s.length(); i++) { if (root.child[0] == null) { root.child[0] = new Trie(); } root = root.child[0]; } root.count++; } void remove(String s) { Trie root = this; for (int i = s.length() - 1; i >= 0; i--) { int index = (s.charAt(i) - '0') % 2; if (root.child[index] == null) { root.child[index] = new Trie(); } root = root.child[index]; } for (int i = 0; i < 18 - s.length(); i++) { if (root.child[0] == null) { root.child[0] = new Trie(); } root = root.child[0]; } root.count--; } int matches(String key) { Trie root = this; for (int i = key.length() - 1; i >= 0; i--) { root = root.child[key.charAt(i) - '0']; if (root == null) { return 0; } } for (int i = 0; i < 18 - key.length(); i++) { root = root.child[0]; if (root == null) { return 0; } } return root.count; } } public static void main(String[]args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); Trie root = new Trie(); while (t-- > 0) { char op; String comm; StringTokenizer st = new StringTokenizer(in.readLine()); op = st.nextToken().charAt(0); comm = st.nextToken(); if (op == '+') { root.add(comm); } else if (op == '-') { root.remove(comm); } else { out.println(root.matches(comm)); } } in.close(); out.close(); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
e5c222c8f91a574a2f89bcbd9c2f4a45
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); new Main().run(in, out); out.close(); } public void run(Reader in, PrintWriter out) { int t = in.ni(); Map<Long, Integer> num2cnt = new HashMap<>(); Map<String, Integer> pat2cnt = new HashMap<>(); for(int i = 0; i < t; i++) { char ch = in.nc(); if(ch == '+') { long val = in.nl(); Integer cnt = num2cnt.get(val); if(cnt == null) { cnt = 0; } num2cnt.put(val, cnt + 1); String pattern = getPattern(val); cnt = pat2cnt.get(pattern); if(cnt == null) { cnt = 0; } pat2cnt.put(pattern, cnt + 1); } else if(ch == '-') { long val = in.nl(); Integer cnt = num2cnt.get(val); num2cnt.put(val, cnt - 1); String pattern = getPattern(val); cnt = pat2cnt.get(pattern); if(cnt == null) { cnt = 0; } pat2cnt.put(pattern, cnt - 1); } else { Integer cnt = pat2cnt.get(addPattern(in.next())); out.println(cnt == null ? 0 : cnt); } } } public String addPattern(String pat) { StringBuilder sb = new StringBuilder(pat); sb = sb.reverse(); while(sb.length() != 18) { sb.append("0"); } return sb.reverse().toString(); } public String getPattern(long number) { StringBuilder sb = new StringBuilder(18); for(int i = 0; i < 18; i++) { long digit = number % 10; number /= 10l; if(digit % 2 == 0) { sb.append(0); } else { sb.append(1); } } return sb.reverse().toString(); } } class Reader { private BufferedReader in; private StringTokenizer st = new StringTokenizer(""); private String delim = " "; public Reader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public String next() { if (!st.hasMoreTokens()) { st = new StringTokenizer(rl()); } return st.nextToken(delim); } public String rl() { try { return in.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } public char nc() { return next().charAt(0); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public double nd() { return Double.parseDouble(next()); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
8d59151a4699afa6373c9155892130b3
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.*; import java.util.Arrays; import java.math.*; import java.io.*; /** * * @author Zach */ public class ACM { public static long simplify(long i){ long x = 2000000000; x*=1000000000; while(x>1){ while(i%(5*x)>=x){ i-=x; } x/=10; } return i; } public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); Hashtable<Long, Integer> h = new Hashtable<Long,Integer>(); for(int i=0; i<n; i++){ String c = in.next(); long x = in.nextLong(); if(c.equals("+")){ if(h.containsKey(simplify(x))){ h.put(simplify(x), h.get(simplify(x))+1); } else{ h.put(simplify(x), 1); } } if(c.equals("-")){ h.put(simplify(x), h.get(simplify(x))-1); } if(c.equals("?")){ if(h.containsKey(x)){ System.out.println(h.get(x)); } else{ System.out.println(0); } } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
edbc22cf08566af3e2e2f86b7bfe962f
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { static int MOD = 1000000007; public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m = 1 << 18; int[] arr = new int[m]; // st = new StringTokenizer(br.readLine()); while (n-- > 0) { String s = br.readLine(); char c = s.charAt(0); long a = Long.parseLong(s.substring(2)); int b = convert(a); if (c == '+') arr[b]++; else if (c == '-') arr[b]--; else System.out.println(arr[b]); } } static int convert(long a) { int val=0,l; for(int i=0;a>0;i++){ val |= (a & 1) << i; a=a/10; } return val; // return a == 0 ? 0 : convert(a / 10) * 2 + (int) (a % 2); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
588db2f1d37618d5eea5f8e6db409293
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { static int MOD = 1000000007; public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m = 1 << 18; int[] arr = new int[m]; // st = new StringTokenizer(br.readLine()); while (n-- > 0) { String s = br.readLine(); char c = s.charAt(0); long a = Long.parseLong(s.substring(2)); int b = convert(a); if (c == '+') arr[b]++; else if (c == '-') arr[b]--; else System.out.println(arr[b]); } } static int convert(long a) { return a == 0 ? 0 : convert(a / 10) * 2 + (int) (a % 2); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
e749325934d5669c5d333e0b35fb597b
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class SonyaAndQueries { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st; int[] pow2 = new int[20]; pow2[0] = 1; for (int i = 1; i < 20; i++) { pow2[i] = pow2[i - 1] * 2; } int[] count = new int[1000001]; for (int t = Integer.parseInt(br.readLine()); t-- > 0; ) { st = new StringTokenizer(br.readLine()); char op = st.nextToken().charAt(0); String number = st.nextToken(); int num = 0; for (int i = 0, j = number.length() - 1; j >= 0; i++, j--) { int digit = (number.charAt(i) - '0') % 2; if (digit == 1) { num += pow2[j]; } } if (op == '+') { count[num]++; } else if (op == '-') { count[num]--; } else { out.println(count[num]); } } out.close(); } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
be374b0ea94ed99244ec2473c2de0e09
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/* * UMANG PANCHAL * DAIICT */ import java.util.*; import java.io.*; import java.math.*; import java.util.Comparator; public class Main { private static final Comparator<? super Integer> Comparator = null; static LinkedList<Integer> adj[]; static ArrayList<Integer> adj1[]; static int[] color,visited1; static boolean b[],visited[],possible; static int level[]; static Map<Integer,HashSet<Integer>> s; static int totalnodes,colored; static int count[]; static long sum[]; static int nodes; static long ans=0; static long[] as=new long[10001]; static long c1=0,c2=0; static int[] a,d,k; static int max=100000000; static long MOD = 1000000007,sm=0,m=Long.MIN_VALUE; static boolean[] prime=new boolean[1000005]; static int[] levl; static int[] eat; static int price[]; static int res[],par[]; static int result=0; static int[] root,size,du,dv; static long p=Long.MAX_VALUE; static int start,end; static boolean[] vis1,vis2; // --------------------My Code Starts Here---------------------- public static void main(String[] args) throws IOException { in=new InputReader(System.in); w=new PrintWriter(System.out); HashMap<String,Long> hm=new HashMap<String,Long>(); int n=ni(); while(n-->0) { String[] s=ns().split(" "); char c=s[0].charAt(0); if(c=='+') { StringBuilder sb=new StringBuilder(""); for(int i=0;i<s[1].length();i++) { if((s[1].charAt(i)-'0')%2==0) sb.append('0'); else sb.append('1'); } String t=sb.toString(); //w.println(s[1]+" "+t); if(hm.containsKey(t)) hm.put(t,hm.get(t)+1); else hm.put(t,(long) 1); int i; for(i=0;i<t.length();i++) { if(t.charAt(i)=='1') break; } //w.println("i: "+i); if(i!=0) { StringBuilder nb=new StringBuilder(""); for(int ni=i;ni<t.length();ni++) { nb.append(t.charAt(ni)); } String nt=nb.toString(); //w.println(s[1]+" "+nt); if(hm.containsKey(nt)) hm.put(nt,hm.get(nt)+1); else hm.put(nt,(long) 1); while(!nt.equals(t)) { nt='0'+nt; if(nt.equals(t)) break; if(hm.containsKey(nt)) hm.put(nt,hm.get(nt)+1); else hm.put(nt,(long) 1); //w.println(s[1]+" "+t); } } while(t.length()<18) { t='0'+t; if(hm.containsKey(t)) hm.put(t,hm.get(t)+1); else hm.put(t,(long) 1); //w.println(s[1]+" "+t); } //w.println(); } else if(c=='-') { StringBuilder sb=new StringBuilder(""); for(int i=0;i<s[1].length();i++) { if((s[1].charAt(i)-'0')%2==0) sb.append('0'); else sb.append('1'); } String t=sb.toString(); if(hm.containsKey(t)) hm.put(t,hm.get(t)-1); int i; for(i=0;i<t.length();i++) { if(t.charAt(i)=='1') break; } if(i!=0) { StringBuilder nb=new StringBuilder(""); for(int ni=i;ni<t.length();ni++) { nb.append(t.charAt(ni)); } String nt=nb.toString(); if(hm.containsKey(nt)) hm.put(nt,hm.get(nt)-1); while(!nt.equals(t)) { nt='0'+nt; if(nt.equals(t)) break; if(hm.containsKey(nt)) hm.put(nt,hm.get(nt)-1); //w.println(s[1]+" "+t); } } while(t.length()<18) { t='0'+t; if(hm.containsKey(t)) hm.put(t,hm.get(t)-1); } } else { if(hm.containsKey(s[1])) w.println(hm.get(s[1])); else w.println(0); } } w.close(); } // --------------------My Code Ends Here------------------------ /* * PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return Integer.compare(o2,o1); } }); * * */ public static void bfs1(int u) { Queue<Integer> q=new LinkedList(); q.add(u); vis1[u]=true; while(!q.isEmpty()) { //w.print(1); int p=q.poll(); for(int i=0;i<adj[p].size();i++) { if(!vis1[adj[p].get(i)]) { du[adj[p].get(i)]=du[p]+1; q.add(adj[p].get(i)); vis1[adj[p].get(i)]=true; } } } } public static void bfs2(int u) { Queue<Integer> q=new LinkedList(); q.add(u); vis2[u]=true; while(!q.isEmpty()) { int p=q.poll(); for(int i=0;i<adj[p].size();i++) { if(!vis2[adj[p].get(i)]) { dv[adj[p].get(i)]=dv[p]+1; q.add(adj[p].get(i)); vis2[adj[p].get(i)]=true; } } } } public static void buildgraph(int n) { adj=new LinkedList[n+1]; visited=new boolean[n]; level=new int[n]; par=new int[n]; for(int i=0;i<=n;i++) { adj[i]=new LinkedList<Integer>(); } } /*public static long kruskal(Pair[] p) { long ans=0; int w=0,x=0,y=0; for(int i=0;i<p.length;i++) { w=p[i].w; x=p[i].x; y=p[i].y; if(root(x)!=root(y)) { ans+=w; union(x,y); } } return ans; }*/ static class Pair implements Comparable<Pair> { int c,p,index; Pair(int c,int p,int index) { this.c=c; this.p=p; this.index=index; } public int compareTo(Pair o) { return Integer.compare(o.p,this.p); } } static class npair implements Comparable<npair> { int a,b; npair(int a,int b) { this.a=a; this.b=b; //this.index=index; } public int compareTo(npair o) { // TODO Auto-generated method stub return Integer.compare(this.a,o.a); } } public static int root(int i) { while(root[i]!=i) { root[i]=root[root[i]]; i=root[i]; } return i; } public static void init(int n) { root=new int[n+1]; for(int i=1;i<=n;i++) root[i]=i; } public static void union(int a,int b) { int root_a=root(a); int root_b=root(b); root[root_a]=root_b; // size[root_b]+=size[root_a]; } public static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (long i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } public static String ns() { return in.nextLine(); } public static int ni() { return in.nextInt(); } public static long nl() { return in.nextLong(); } public static int[] na(int n) { int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=ni(); return a; } public static long[] nla(int n) { long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nl(); return a; } public static void sieve() { int n=prime.length; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*2; i <n; i += p) prime[i] = false; } } } public static String rev(String s) { StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } static InputReader in; static PrintWriter w; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
a56c6b9f148d3c285c5c59ca7a88cf68
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.*; import java.util.*; /** * Created by Алексей on 06/26/2016. */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.random; import static java.lang.Math.*; public class TriangleEasy { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { interface Tree{ void add(String value); void delete(String value); int find(String value); } class ArrayTree implements Tree{ private int []arratTree; private int deep = 19; private int r = (2<<deep)*4; private int l =0; ArrayTree(){ arratTree = new int[r]; } private int treeRun(int v, int l, int r, String value, int idx, char operator){ if(operator=='a') { arratTree[v]++; }else if(operator=='d') { arratTree[v]--; } if(idx==-1){ return arratTree[v]; }else{ int middle = (l+r)/2; if(value.charAt(idx)=='0'){ return treeRun (v*2, l, middle, value, --idx, operator); }else{ return treeRun (v*2+1, middle+1, r, value, --idx, operator); } } } @Override public void add(String value) { treeRun(1,0,(2<<deep)-1, value, deep-1, 'a'); } @Override public void delete(String value) { treeRun(1,0,(2<<deep)-1, value, deep-1, 'd'); } @Override public int find(String value) { return treeRun(1,0,(2<<deep)-1, value, deep-1, 'f'); } } class ListTree implements Tree{ private Node root; ListTree(){ root = new Node(); } private class Node{ Node l; Node r; int value; } private int treeRun(Node node, String value, int idx, char operator){ if(operator=='a'){ node.value++; }else if(operator=='d'){ node.value--; } if(idx==-1){ return node.value; }else if(value.charAt(idx)=='0'){ if(node.l==null){ node.l = new Node(); } return treeRun(node.l, value, --idx, operator); }else{ if(node.r==null){ node.r = new Node(); } return treeRun(node.r, value, --idx, operator); } } @Override public void add(String value){ treeRun(root, value, value.length()-1, 'a'); } @Override public int find(String value){ return treeRun(root, value, value.length()-1, 'f'); } @Override public void delete(String value){ treeRun(root, value, value.length()-1, 'd'); } } private String convertFun(long value){ StringBuffer str =new StringBuffer(""); for(long i=1; str.length()<19; i*=10){ long sum = ((value%(i*10))/i)%2; String digit = String.valueOf(sum); str.append(digit); } str.reverse(); return str.toString(); } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); Tree bTree =new ArrayTree(); while(t-->0){ char queries = in.nextChar(); long value = in.nextLong(); if(queries=='+') { bTree.add(convertFun(value)); }else if(queries=='-'){ bTree.delete(convertFun(value)); }else{ StringBuffer convert = new StringBuffer(String.valueOf(value)); while(convert.length()<19){ convert.insert(0,'0'); } out.println(bTree.find(convert.toString())); } } } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
4414322295d7365b44fca80705484286
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.*; import java.util.*; /** * Created by Алексей on 06/26/2016. */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.random; import static java.lang.Math.*; public class TriangleEasy { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { class Tree{ Node root; Tree(){ root = new Node(); } class Node{ Node l; Node r; int value; } private int treeRun(Node node, String value, int idx, char operator){ if(operator=='a'){ node.value++; }else if(operator=='d'){ node.value--; } if(idx==-1){ if(operator=='f') { return node.value; }else{ return 0; } }else if(value.charAt(idx)=='0'){ if(node.l==null){ node.l = new Node(); } return treeRun(node.l, value, --idx, operator); }else{ if(node.r==null){ node.r = new Node(); } return treeRun(node.r, value, --idx, operator); } } void add(String value){ treeRun(root, value, value.length()-1, 'a'); } int find(String value){ return treeRun(root, value, value.length()-1, 'f'); } void delete(String value){ treeRun(root, value, value.length()-1, 'd'); } } String convertFun(long value){ StringBuffer str =new StringBuffer(""); for(long i=1; str.length()<19; i*=10){ long sum = ((value%(i*10))/i)%2; String digit = String.valueOf(sum); str.append(digit); } str.reverse(); // System.out.println(str); return str.toString(); } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); Tree bTree = new Tree(); while(t-->0){ char queries = in.nextChar(); long value = in.nextLong(); if(queries=='+') { bTree.add(convertFun(value)); }else if(queries=='-'){ bTree.delete(convertFun(value)); }else{ StringBuffer convert = new StringBuffer(String.valueOf(value)); while(convert.length()<19){ convert.insert(0,'0'); } System.out.println(bTree.find(convert.toString())); } } } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write(1); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
47fb92a88b07300ac523c3265d05ab52
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.*; import java.util.*; /** * Created by Алексей on 06/26/2016. */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.random; import static java.lang.Math.*; public class TriangleEasy { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { interface Tree{ void add(String value); void delete(String value); int find(String value); } class ArrayTree implements Tree{ private int []arratTree; private int deep = 19; private int r = (2<<deep)*4; private int l =0; ArrayTree(){ arratTree = new int[r]; } private int treeRun(int v, int l, int r, String value, int idx, char operator){ if(operator=='a') { arratTree[v]++; }else if(operator=='d') { arratTree[v]--; } if(idx==-1){ return arratTree[v]; }else{ int middle = (l+r)/2; if(value.charAt(idx)=='0'){ return treeRun (v*2, l, middle, value, --idx, operator); }else{ return treeRun (v*2+1, middle+1, r, value, --idx, operator); } } } @Override public void add(String value) { treeRun(1,0,(2<<deep)-1, value, deep-1, 'a'); } @Override public void delete(String value) { treeRun(1,0,(2<<deep)-1, value, deep-1, 'd'); } @Override public int find(String value) { return treeRun(1,0,(2<<deep)-1, value, deep-1, 'f'); } } class ListTree implements Tree{ private Node root; ListTree(){ root = new Node(); } private class Node{ Node l; Node r; int value; } private int treeRun(Node node, String value, int idx, char operator){ if(operator=='a'){ node.value++; }else if(operator=='d'){ node.value--; } if(idx==-1){ return node.value; }else if(value.charAt(idx)=='0'){ if(node.l==null){ node.l = new Node(); } return treeRun(node.l, value, --idx, operator); }else{ if(node.r==null){ node.r = new Node(); } return treeRun(node.r, value, --idx, operator); } } @Override public void add(String value){ treeRun(root, value, value.length()-1, 'a'); } @Override public int find(String value){ return treeRun(root, value, value.length()-1, 'f'); } @Override public void delete(String value){ treeRun(root, value, value.length()-1, 'd'); } } private String convertFun(long value){ StringBuffer str =new StringBuffer(""); for(long i=1; str.length()<19; i*=10){ long sum = ((value%(i*10))/i)%2; String digit = String.valueOf(sum); str.append(digit); } str.reverse(); return str.toString(); } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); Tree bTree =new ListTree(); while(t-->0){ char queries = in.nextChar(); long value = in.nextLong(); if(queries=='+') { bTree.add(convertFun(value)); }else if(queries=='-'){ bTree.delete(convertFun(value)); }else{ StringBuffer convert = new StringBuffer(String.valueOf(value)); while(convert.length()<19){ convert.insert(0,'0'); } out.println(bTree.find(convert.toString())); } } } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
9bc1e6c9a859ac16c37a54232bc88151
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.*; /** * Created by Kafukaaa on 16/9/17. */ /* ����scanner.nextLine()ʱ����һ������Ч�ģ����� * */ public class SonyaAndQueries { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); String[] order = new String[t+1]; int[] answer = new int[10000001]; for (int i = 0; i < t+1; i++) { order[i] = scanner.nextLine(); } for (int i = 1; i < t+1; i++) { String pattern = order[i].substring(2); StringBuilder s = new StringBuilder(); for (int j = 0; j < pattern.length(); j++) { if (Integer.parseInt(pattern.substring(j,j+1)) % 2 == 1){ s = s.append("1"); }else { s = s.append("0"); } } int ele = Integer.parseInt(s.toString(),2); if (order[i].substring(0,1).equals("+")){ answer[ele] ++; }else if (order[i].substring(0,1).equals("-")){ answer[ele] --; }else if (order[i].substring(0,1).equals("?")){ System.out.println(answer[ele]); } } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
a76f404dd7abbc36618eccea37e8c37b
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[256]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String args[])throws IOException{ Reader in = new Reader(); Scanner sc = new Scanner(System.in); int n = in.nextInt(); String temp = in.readLine(); HashMap<Integer,Integer> map = new HashMap<>(); for(int i=0;i<n;i++){ String s=in.readLine(); if(s.charAt(0)=='+') add(map,s.substring(2)); else if(s.charAt(0)=='-') remove(map,s.substring(2)); else System.out.println(get_query(map,s.substring(2))); } } static void add(HashMap<Integer,Integer> map,String s){ int n = 0; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); int x = ch-'0'; if(x%2==0) n=n*10+0; else n=n*10+1; } if(map.get(n)==null) map.put(n,1); else{ int f = map.get(n); map.put(n, f+1); } } static void remove(HashMap<Integer,Integer> map,String s){ int n = 0; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); int x = ch-'0'; if(x%2==0) n=n*10+0; else n=n*10+1; } if(map.get(n)==null) return; else{ int f = map.get(n); map.put(n, f-1); } } static int get_query(HashMap<Integer,Integer> map,String s){ int n = 0; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); int x = ch-'0'; if(x%2==0) n=n*10+0; else n=n*10+1; } if(map.get(n)!=null) return map.get(n); else return 0; } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
953a343fb037338c4ae859673008726c
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/** * Created by ankeet on 9/13/16. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.StringTokenizer; public class C714 { static FastReader in = null; static PrintWriter out = null; static PriorityQueue<Long> pq = new PriorityQueue<Long>(); static TrieNode root = new TrieNode(-1); static class TrieNode{ int parity = 0; int size = 0; TrieNode ev = null; TrieNode od = null; public TrieNode( int p) { this.parity = p; } } public static void change(String s, boolean add) { int i = s.length()-1; TrieNode ptr = root; while(i>=0) { ptr.size = ptr.size + (add ? 1 : -1); char c = s.charAt(i); int val = (int) (c - '0'); if ((val % 2 == 0)) { if (ptr.ev == null) ptr.ev = new TrieNode(0); ptr = ptr.ev; } else { if (ptr.od == null) ptr.od = new TrieNode(1); ptr = ptr.od; } i--; } ptr.size = ptr.size + (add? 1 : -1); } public static int count(String s) { int i = s.length()-1; TrieNode ptr = root; while(i>=0) { char c = s.charAt(i); if(c == '0') { if(ptr.ev == null) return 0; ptr = ptr.ev; } else { if(ptr.od == null) return 0; ptr = ptr.od; } i--; } return ptr.size; } public static void solve() { int t = in.nextInt(); for(int i=0; i<t; i++) { char s = in.next().charAt(0); if(s == '+' || s == '-') { long a = in.nextLong(); String q = ""+a; while(q.length() < 25) q = "0"+q; change(q, s == '+'); } if(s == '?') { String seq = in.next(); while(seq.length() < 25) seq = "0"+seq; out.println(count(seq)); } } } public static void main(String[] args) { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } static class FastReader { BufferedReader read; StringTokenizer tokenizer; public FastReader(InputStream in) { read = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(read.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine(){ try { return read.readLine(); } catch(Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = nextInt(); } return a; } public long[] nextLongArr(int n) { long[] a = new long[n]; for(int i=0; i<n; ++i) { a[i] = nextLong(); } return a; } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
1c8399a07cfacfc7650c8e7c50a9d785
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.*; import java.io.*; public class SonyaAndQueries { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); TrieNode root = new TrieNode(); int t = in.nextInt(); HashMap<String, Integer> hm = new HashMap<String, Integer>(); while(t-- > 0) { char c = in.readString().charAt(0); char[] num = new char[18]; Arrays.fill(num, '0'); if(c == '+') { long no = in.nextLong(); char[] tmp = Long.toString(no).toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; for(int i = 0; i < 18; i++) num[i] = ((((int)num[i] - (int)'0')&1) == 0)? '0' : '1'; //out.println(Arrays.toString(num)); String n = new String(num); if(!hm.containsKey(n)) { hm.put(n, 0); insertString(root, n); } hm.put(n, hm.get(n) + 1); } else if(c == '-') { long no = in.nextLong(); char[] tmp = Long.toString(no).toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; for(int i = 0; i < 18; i++) num[i] = ((((int)num[i] - (int)'0')&1) == 0)? '0' : '1'; //out.println(Arrays.toString(num)); String n = new String(num); hm.put(n, hm.get(n) - 1); if(hm.get(n) == 0) { hm.remove(n); removeString(root, n); } } else { char[] tmp = in.readString().toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; //out.println(Arrays.toString(num)); String n = new String(num); boolean inn = contains(root, n); out.println("" + (inn ? hm.get(n) : 0)); } } out.close(); } public static class TrieNode { int count; boolean isLeaf; TrieNode[] children; public TrieNode() { this.count = 0; this.isLeaf = false; this.children = new TrieNode[2]; } } public static void insertString(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; if(curr.children[index] == null) curr.children[index] = new TrieNode(); curr = curr.children[index]; curr.count++; } if(curr != null) curr.isLeaf = true; } public static boolean contains(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; if (curr.children[index] == null) return false; curr = curr.children[index]; } return curr.isLeaf; } public static void removeString(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; TrieNode child = curr.children[index]; if(child == null) return; if(child.count == 1){ curr.children[index] = null; return; } else { child.count--; curr = child; } } if(curr != null) curr.isLeaf = false; } static class Node implements Comparable<Node> { int next; long dist; public Node(int u, int v) { this.next = u; this.dist = v; } public void print() { out.println(next + " " + dist + " "); } public int compareTo(Node n) { return Integer.compare(-this.next, -n.next); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
7ebe4d6b3482a3ce6f73421e69f336d2
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.util.*; import java.io.*; public class SonyaAndQueries { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); TrieNode root = new TrieNode(); int t = in.nextInt(); HashMap<String, Integer> hm = new HashMap<String, Integer>(); while(t-- > 0) { char c = in.readString().charAt(0); char[] num = new char[18]; Arrays.fill(num, '0'); if(c == '+') { long no = in.nextLong(); char[] tmp = Long.toString(no).toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; for(int i = 0; i < 18; i++) num[i] = ((((int)num[i] - (int)'0')&1) == 0)? '0' : '1'; //out.println(Arrays.toString(num)); String n = new String(num); if(!hm.containsKey(n)) { hm.put(n, 0); insertString(root, n); } hm.put(n, hm.get(n) + 1); } else if(c == '-') { long no = in.nextLong(); char[] tmp = Long.toString(no).toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; for(int i = 0; i < 18; i++) num[i] = ((((int)num[i] - (int)'0')&1) == 0)? '0' : '1'; //out.println(Arrays.toString(num)); String n = new String(num); hm.put(n, hm.get(n) - 1); if(hm.get(n) == 0) { hm.remove(n); removeString(root, n); } } else { char[] tmp = in.readString().toCharArray(); int len = tmp.length; for(int i = 0; i < len; i++) num[18 - len + i] = tmp[i]; //out.println(Arrays.toString(num)); String n = new String(num); boolean checkkkkk = contains(root, n); int result = 0; if(checkkkkk) result = hm.get(n); System.out.println(result); } } out.close(); } public static class TrieNode { int count; boolean isLeaf; TrieNode[] children; public TrieNode() { this.count = 0; this.isLeaf = false; this.children = new TrieNode[2]; } } public static void insertString(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; if(curr.children[index] == null) curr.children[index] = new TrieNode(); curr = curr.children[index]; curr.count++; } if(curr != null) curr.isLeaf = true; } public static boolean contains(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; if (curr.children[index] == null) return false; curr = curr.children[index]; } return curr.isLeaf; } public static void removeString(TrieNode root, String s) { TrieNode curr = root; for (char ch : s.toCharArray()) { int index = (int)ch - (int)'0'; TrieNode child = curr.children[index]; if(child == null) return; if(child.count == 1){ curr.children[index] = null; return; } else { child.count--; curr = child; } } if(curr != null) curr.isLeaf = false; } static class Node implements Comparable<Node> { int next; long dist; public Node(int u, int v) { this.next = u; this.dist = v; } public void print() { out.println(next + " " + dist + " "); } public int compareTo(Node n) { return Integer.compare(-this.next, -n.next); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
4ad7cdf66e432588ca80b9674eb213a6
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
/** * Code Author Savaliya Sagar * DA-IICT */ import java.awt.image.ReplicateScaleFilter; import java.io.*; import java.math.*; import java.util.*; import javax.swing.RepaintManager; public class C714 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); //----------My Code---------- HashMap<String,Integer> h = new HashMap<String,Integer>(); int t = in.nextInt(); while(t-->0){ String str = in.nextLine(); String temp[] = str.split(" "); if(temp[0].equals("+")){ String s1 = stringconverter(temp[1]); int z = 0; if(h.containsKey(s1)){ z = h.get(s1); } h.put(s1,z+1); }else if(temp[0].equals("-")){ String s1 = stringconverter(temp[1]); h.put(s1,h.get(s1)-1); } else if(temp[0].equals("?")){ int count = 0; String s1 = Long.toString(Long.parseLong(temp[1])); if(h.containsKey(s1)) count += h.get(s1); out.println(count); } } //---------------The End------------------ out.close(); } public static String stringconverter(String t){ StringBuffer ss = new StringBuffer(t); for(int i=0;i<ss.length();i++){ int l = Character.getNumericValue(ss.charAt(i)); if(l%2==0) ss.setCharAt(i,'0'); else ss.setCharAt(i, '1'); } return Long.toString(Long.parseLong(ss.toString())); } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } static class Scanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
2e54d5de07531c0e03970b1575e59bfc
train_001.jsonl
1473784500
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:  +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.  -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ public static final int mod = 1000003; public static void main(String[] args)throws IOException { // TODO Auto-generated method stub InputStream input = System.in; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Reader in = new Reader(); StringBuilder sss = new StringBuilder(""); int t = Integer.parseInt(br.readLine()); Node root = new Node(); while(t-- >0) { String s = br.readLine(); if(s.charAt(0) == '+' ) { String x = s.substring(2); StringBuilder sb = new StringBuilder(""); for(int i=0; i<19-x.length(); i++) sb.append("0"); add(root,sb.toString()+x); } else if(s.charAt(0) == '-') { String x = s.substring(2); StringBuilder sb = new StringBuilder(""); for(int i=0; i<19-x.length(); i++) sb.append("0"); remove(root,sb.toString()+x); } else { String pattern = s.substring(2); StringBuilder sb = new StringBuilder(""); for(int i=0; i<19-pattern.length(); i++) sb.append("0"); sss.append(find(root,sb.toString()+pattern)+"\n"); } } System.out.println(sss.toString()); } static int find(Node root,String x) {//System.out.println(x); if(x.length() == 0) { return root.dc; } int i = (x.charAt(x.length()-1)-'0')%2; if(root.child[i] == null) return 0; return find(root.child[i],x.substring(0,x.length()-1)); } static void remove(Node root,String x) { if(x.length() == 0) { root.c--; root.dc--; return ; } int i = (x.charAt(x.length()-1)-'0')%2; remove(root.child[i],x.substring(0,x.length()-1)); root.dc--; } static void add(Node root,String x) { if(x.length() == 0) { root.c++; root.dc++; return ; } int i = (x.charAt(x.length()-1)-'0')%2; if(root.child[i] == null) { root.child[i] = new Node(); } add(root.child[i],x.substring(0,x.length()-1)); root.dc++; } static class Node{ Node child[]; int c ,dc; Node() { child = new Node[2]; c = 0; dc = 0; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0", "4\n+ 200\n+ 200\n- 200\n? 0"]
1 second
["2\n1\n2\n1\n1", "1"]
NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
Java 8
standard input
[ "data structures", "implementation" ]
0ca6c7ff6a2d110a8f4153717910378f
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai &lt; 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
1,400
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
standard output
PASSED
326eec9d4b6ab8e80ade2a2057a03cb5
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class cf { static final Scanner sc = new Scanner(System.in); static final int mod = (int) (1e9 + 7); public static void main(String[] args) throws IOException { Reader r= new Reader(); PrintWriter out; out = new PrintWriter(System.out); // int testcases = sc.nextInt(); // while (testcases-- > 0) { int n = r.nextInt(); if (n==2) { r.nextInt(); r.nextInt(); System.out.println(0); return; } Vector<Integer> v[] = new Vector[n + 1]; int[][] a = new int[n - 1][2]; Vector<Integer> vector = new Vector<>(); Set<Integer> set = new HashSet<>(); for (int i = 0; i < n - 1; i++) { a[i][0] = r.nextInt(); a[i][1] = r.nextInt(); if (v[a[i][0]] == null) { v[a[i][0]] = (Vector<Integer>) vector.clone(); } if (v[a[i][1]] == null) { v[a[i][1]] = (Vector<Integer>) vector.clone(); } v[a[i][0]].add(a[i][1]); v[a[i][1]].add(a[i][0]); } for (int i = 1; i < v.length; i++) { if (v[i].size() == 1) { set.add(i); } } int min = set.size() - 1, max = set.size(); for (int i = 0; i < a.length; i++) { if (set.contains(a[i][0]) || set.contains(a[i][1])) { out.println(min); min--; } else { out.println(max); max++; } } out.flush(); // } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
97469238d2f307e07af5b15f4643974c
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long sx = 0, sy = 0, m = (long) (1e9 + 7); static ArrayList<pair>[] a; static int[][] dp; static long[] farr; static boolean b = true; // static HashMap<Long, Integer> hm = new HashMap<>(); static TreeMap<Integer, Integer> hm = new TreeMap<>(); public static PrintWriter out; static ArrayList<pair> ans = new ArrayList<>(); static long[] fact = new long[(int) 1e6]; static StringBuilder sb = new StringBuilder(); static boolean cycle = false; static long mod = 998244353; public static void main(String[] args) throws IOException { Reader scn = new Reader(); int n = scn.nextInt(); a = new ArrayList[n + 1]; for(int i=0; i<=n; i++) a[i] = new ArrayList<>(); for (int i = 1; i <= n - 1; i++) { int x = scn.nextInt(), y = scn.nextInt(); a[x].add(new pair(y, i)); a[y].add(new pair(x, i)); } int[] ans = new int[n]; Arrays.fill(ans, -1); int cnt = 0; for (int i = 1; i <= n; i++) { if (a[i].size() == 1 && cnt<=n-2) { ans[a[i].get(0).no] = cnt++; } } for (int i = 1; i < ans.length; i++) if (ans[i] == -1) ans[i] = cnt++; for (int i = 1; i <ans.length; i++) System.out.println(ans[i]); } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if (a == 0) // return b; // // return gcd(b % a, a); // } // static class comp implements Comparator<Integer> { // // @Override // public int compare(Integer o1, Integer o2) { // // return (int) (o2 - o1); // } // // } // public static long pow(long a, long b) { // // if(b<0)return 0; // if (b == 0 || b == 1) // return (long) Math.pow(a, b); // // if (b % 2 == 0) { // // long ret = pow(a, b / 2); // ret = (ret % mod * ret % mod) % mod; // return ret; // } // // else { // return ((pow(a, b - 1) % mod) * a % mod) % mod; // } // } private static class pair implements Comparable<pair> { int v, no; pair(int a, int b) { v = a; no = b; } @Override public int compareTo(pair o) { return 1; } } public static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000 + 1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } 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[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } // kickstart - Solution // atcoder - Main } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
ec31ce9b265caf357c66ea9ef3b3c92a
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
/* *created by Kraken on 12-05-2020 at 16:42 */ //package com.kraken.cf.practice; import java.util.*; import java.io.*; public class C1325 { public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); int[] degree = new int[n + 1]; int[][] edges = new int[n - 1][2]; for (int i = 0; i < n - 1; i++) { edges[i][0] = sc.nextInt(); edges[i][1] = sc.nextInt(); degree[edges[i][0]]++; degree[edges[i][1]]++; } int m = -1; for (int i = 1; i <= n; i++) if (degree[i] >= 3) { m = i; break; } StringBuilder sb = new StringBuilder(); if (m == -1) { for (int i = 0; i < n - 1; i++) sb.append(i + "\n"); System.out.print(sb.toString()); return; } int[] res = new int[n - 1]; Arrays.fill(res, -1); int l = 0, x = 0; for (int[] edge : edges) { if (edge[0] == m || edge[1] == m) res[l] = x++; l++; } for (int i = 0; i < n - 1; i++) { if (res[i] == -1) res[i] = x++; sb.append(res[i] + "\n"); } System.out.print(sb.toString()); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
f0960b247deeef0cf994e186dbed5699
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; import java.util.*; import java.util.ArrayList; public final class Codeforces { static int p=1000000000,ans[],parity,s,e; static ArrayList<edge>g; static HashMap<Integer,ArrayList<edge>>map; public static void main(String[] args) throws Exception{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); FastReader sc = new FastReader(); int n,u,v; n=sc.nextInt(); ans=new int[n-1]; map=new HashMap<>(); g=new ArrayList<>(); pair po[]=new pair[n-1]; for(int i=0;i<n-1;i++) { u=sc.nextInt(); v=sc.nextInt(); add_edge(u,v,i); } s=0; for(Integer p:map.keySet()) { if(map.get(p).size()>=3) { ArrayList<edge>list=map.get(p); list.get(0).weight=s++; list.get(1).weight=s++; list.get(2).weight=s++; break; } } for(edge ee:g) { if(ee.weight==-1)ee.weight=s++; } for(edge ee:g)out.write(ee.weight+" "+'\n'); out.write('\n'); out.flush(); } static class pair { int i,v,weight=-1; pair(int v,int i) { this.v=v; this.i=i; } } static class edge{ int u,v,id,weight=-1; edge(int u,int v,int id) { this.u=u;this.v=v;this.id=id; } } public static void add_edge(int u,int v,int id) { edge e=new edge(u,v,id); g.add(e); if(map.containsKey(u)) { ArrayList<edge>list=map.get(u); list.add(e); map.put(u,list); } else { ArrayList<edge>list=new ArrayList<>(); list.add(e); map.put(u, list); } if(map.containsKey(v)) { ArrayList<edge>list=map.get(v); list.add(e); map.put(v,list); } else { ArrayList<edge>list=new ArrayList<>(); list.add(e); map.put(v, list); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
305910e615142ce27f44158fd98050f0
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] numberOfEdgesFrom = new int[n]; int[][] edges = new int[n - 1][2]; int u, v; for (int i = 0; i < n - 1; i++) { u = scanner.nextInt() - 1; v = scanner.nextInt() - 1; edges[i][0] = u; edges[i][1] = v; numberOfEdgesFrom[u]++; numberOfEdgesFrom[v]++; } int nLists = 0; for (int i = 0; i < n; i++) { if (numberOfEdgesFrom[i] == 1) nLists++; } if (nLists < 3) { for (int i = 0; i < n - 1; i++) { System.out.print(i + " "); } } else { nLists = 3; int counter = 3; for (int i = 0; i < n - 1; i++) { if (nLists > 0 && (numberOfEdgesFrom[edges[i][0]] == 1 || numberOfEdgesFrom[edges[i][1]] == 1)) { nLists--; System.out.print(nLists + " "); } else { System.out.print(counter + " "); counter++; } } } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
69502bf4e025741593758add4ff56d69
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; public class cf1325_Div2_C { public static class Edge{ int val = -1; int pos = -1; int a; int b; public Edge(int x, int y, int p) { pos = p; a = x; b = y; } } public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); int n = in.nextInt(); Edge[] edges = new Edge[n - 1]; ArrayList<Edge>[] tree = new ArrayList[n]; for (int i = 0; i < n; i++) tree[i] = new ArrayList<Edge>(); for (int i = 0; i < n - 1; i++) { edges[i] = new Edge(in.nextInt() - 1, in.nextInt() - 1, i); tree[edges[i].a].add(edges[i]); tree[edges[i].b].add(edges[i]); } int add = 0; boolean flag = false; for (int i = 0; i < n && !flag; i++) { if (tree[i].size() >= 3) { flag = true; for (Edge x: tree[i]) { x.val = add; add++; } } } for (int i = 0; i < n; i++) { for (Edge x: tree[i]) { if (x.val != -1) continue; x.val = add; add++; } } for (int i = 0; i < n - 1; i++) { System.out.println(edges[i].val); } } public static void shuffle(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int rPos = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[rPos]; arr[rPos]=temp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
b6a75aeea60a7cdffd6b6319d1071e2b
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class Solution { /*static ArrayList<Integer> ar[]; static boolean vis[]; static void dfs(int s) { vis[s]=true; c++; for(int j=0;j<ar[s].size();j++) { if(vis[ar[s].get(j)]==false) dfs(ar[s].get(j)); } }*/ /*static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0, k=1; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } }*/ public static void main(String args[])throws Exception { FastReader in = new FastReader(System.in); int q = 1,i,j; StringBuilder sb = new StringBuilder(); int n=in.nextInt(),res=0; ArrayList<Integer> tree[]=new ArrayList[n+1]; for(i=0;i<=n;i++) tree[i]=new ArrayList<Integer>(); ArrayList<Integer> ar[]=new ArrayList[n+1]; for(i=0;i<=n;i++) ar[i]=new ArrayList<Integer>(); int ans[]=new int[n]; for(i=1;i<n;i++) { int x=in.nextInt(); int y=in.nextInt(); tree[x].add(y); tree[y].add(x); ar[x].add(i); ar[y].add(i); } HashSet<Integer> s=new HashSet<>(); for(i=1;i<=n;i++) { if(tree[i].size()>2) { res=1; s.add(ar[i].get(0)); s.add(ar[i].get(1)); s.add(ar[i].get(2)); ans[ar[i].get(0)]=0; ans[ar[i].get(1)]=1; ans[ar[i].get(2)]=2; break; } } if(res==0) { for(i=0;i<n-1;i++) sb.append(i+"\n"); } else { int k=3; for(i=1;i<n;i++) { if(!s.contains(i)) ans[i]=k++; sb.append(ans[i]+"\n"); } } //sb.append(res+"\n"); //System.out.println(res); System.out.println(sb); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
5b82d7dd1eaaf873a7c43cabdd539394
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.HashMap; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<List<Integer>> graph = new ArrayList<>(); Map<Integer, Map<Integer, Integer>> colore = new HashMap<>(); public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } List<Integer> order = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int v, u; v = in.nextInt() - 1; u = in.nextInt() - 1; addEdge(v, u); addEdge(u, v); order.add(v); order.add(u); } int start = 0; for (int i = 0; i < n; i++) { if (graph.get(i).size() >= 3) { int v = i; for (int j = 0; j < graph.get(i).size(); j++) { int u = graph.get(i).get(j); if (!colore.containsKey(v)) colore.put(v, new HashMap<>()); colore.get(v).put(u, start); if (!colore.containsKey(u)) colore.put(u, new HashMap<>()); colore.get(u).put(v, start); start++; } break; } } for (int i = 0; i < order.size(); i += 2) { int v = order.get(i); int u = order.get(i + 1); if (colore.containsKey(v) && colore.get(v).containsKey(u)) { out.println(colore.get(v).get(u)); } else { out.println(start); start++; } } } private void addEdge(int v, int u) { graph.get(v).add(u); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
9dbde77aa3997cc56bbce5f4435489f7
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
//package CodeforcesProject; import java.io.*; import java.lang.*; import java.util.*; import java.util.function.BiFunction; public class Main extends IO { static Set<Integer> leafs = new HashSet<>(); static List<int[]> buffer = new ArrayList<>(); static int[] knot; public static void main(String[] args) throws Exception { int quantity = readInt(); Graph graph = new Graph(); graph.edgesMatrixToDefault(quantity, quantity - 1, true, null); if (quantity == 2){ System.out.println(0); return; } graph.dfs(0); int ansLeaf = 1; int ans = leafs.size(); for (int[] value : buffer) { if ((value[0] == knot[0] && value[1] == knot[1]) || (value[1] == knot[0] && value[0] == knot[1])) { writeInt(0, "\n"); } else if ((value[0] == knot[0] && value[1] == knot[2]) || (value[1] == knot[0] && value[0] == knot[2])) { writeInt(quantity - 2, "\n"); } else if (leafs.contains(value[0]) || leafs.contains(value[1])) { writeInt(ansLeaf++, "\n"); } else { writeInt(ans++, "\n"); } } print(); } } class math { protected static int remains = 0x989687; protected static int gcd(int a, int b) { // NOD if (b == 0) { return a; } return gcd(b, a % b); } protected static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static float gcd(float a, float b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double gcd(double a, double b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double lcm(double a, double b) { // NOK return a / gcd(a, b) * b; } protected static float lcm(float a, float b) { // NOK return a / gcd(a, b) * b; } protected static int lcm(int a, int b) { // NOK return a / gcd(a, b) * b; } protected static long lcm(long a, long b) { return a / gcd(a, b) * b; } protected static double log(double value, int base) { return Math.log(value) / Math.log(base); } protected static long factorial(int number) { if (number < 0) { return 0; } return solveFactorial(number); } private static long solveFactorial(int number) { if (number > 0) { return solveFactorial(number - 1) * number; } return 1; } } class Int implements Comparable<Integer> { protected int value; Int(int value) { this.value = value; } @Override public int compareTo(Integer o) { return (this.value < o) ? -1 : ((this.value == o) ? 0 : 1); } @Override public boolean equals(Object obj) { if (obj instanceof Integer) { return value == (Integer) obj; } return false; } @Override public int hashCode() { return value; } @Override protected void finalize() throws Throwable { super.finalize(); } } class Fraction<T extends Number> extends Pair { private Fraction(T dividend, T divider) { super(dividend, divider); reduce(); } protected static <T extends Number> Fraction<T> createFraction(T dividend, T divider) { return new Fraction<>(dividend, divider); } protected void reduce() { if (getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); int gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); long gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); float gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); double gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } } protected void addWithoutReturn(Fraction number) throws UnsupportedOperationException { add(number, 0); } private Fraction add(Fraction number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); Integer Dividend1 = (Integer) number.getFirstElement(); Integer Divider1 = (Integer) number.getSecondElement(); Integer lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); Long Dividend1 = (Long) number.getFirstElement(); Long Divider1 = (Long) number.getSecondElement(); Long lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); Float Dividend1 = (Float) number.getFirstElement(); Float Divider1 = (Float) number.getSecondElement(); Float lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); Double Dividend1 = (Double) number.getFirstElement(); Double Divider1 = (Double) number.getSecondElement(); Double lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else { throw new UnsupportedOperationException(); } } protected Fraction addWithReturn(Fraction number) { return add(number, 1); } protected void multiplyWithoutReturn(Fraction number) throws UnsupportedOperationException { multiply(number, 0); } protected Fraction multiplyWithReturn(Fraction number) throws UnsupportedOperationException { return multiply(number, 1); } private Fraction multiply(Fraction number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer first = (Integer) getFirstElement() * (Integer) number.getFirstElement(); Integer second = (Integer) getSecondElement() * (Integer) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long first = (Long) getFirstElement() * (Long) number.getFirstElement(); Long second = (Long) getSecondElement() * (Long) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float first = (Float) getFirstElement() * (Float) number.getFirstElement(); Float second = (Float) getSecondElement() * (Float) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double first = (Double) getFirstElement() * (Double) number.getFirstElement(); Double second = (Double) getSecondElement() * (Double) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else { throw new UnsupportedOperationException(); } } } class Pair<T, T1> implements Cloneable { private T first; private T1 second; Pair(T obj, T1 obj1) { first = obj; second = obj1; } protected static <T, T1> Pair<T, T1> createPair(T element, T1 element1) { return new Pair<>(element, element1); } protected T getFirstElement() { return first; } protected T1 getSecondElement() { return second; } protected void setFirst(T element) { first = element; } protected void setSecond(T1 element) { second = element; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) { return false; } Pair pair = (Pair) obj; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + (first == null ? 0 : first.hashCode()); return 31 * hashCode + (second == null ? 0 : second.hashCode()); } @Override public Object clone() { return Pair.createPair(first, second); } } class Graph { private int[][] base; private boolean[] used; private int quantity; private Integer[] ancestor; public int[][] getBase() { return base.clone(); } public boolean[] getUsed() { return used.clone(); } public int getQuantity() { return quantity; } public Integer[] getAncestor() { return ancestor.clone(); } public void setBase(int[][] base) { this.base = base; } protected void start(int length) { used = new boolean[length]; ancestor = new Integer[length]; Arrays.fill(ancestor, -1); quantity = 0; } protected void edgesMatrixToDefault(int length, int quantity, boolean readConsole, int[][] value) throws Exception { base = new int[length][]; List<ArrayList<Integer>> inputBase = new ArrayList<>(); for (int i = 0; i < length; i++) { inputBase.add(new ArrayList<>()); } for (int i = 0; i < quantity; i++) { int[] input = readConsole ? IO.readArrayInt(" ") : value[i]; Main.buffer.add(input); inputBase.get(input[0] - 1).add(input[1] - 1); //inputBase.get(input[0] - 1).add(input[2]); // price inputBase.get(input[1] - 1).add(input[0] - 1); //inputBase.get(input[1] - 1).add(input[2]); // price } for (int i = 0; i < length; i++) { base[i] = inputBase.get(i).stream().mapToInt(Integer::intValue).toArray(); } start(length); } protected void adjacencyMatrixToDefault(int length, int not, boolean readConsole, int[][] value) throws Exception { this.base = new int[length][]; List<Integer> buffer = new ArrayList<>(); for (int i = 0; i < length; i++) { int[] InputArray = readConsole ? IO.readArrayInt(" ") : value[i]; for (int index = 0; index < length; index++) { if (i != index && InputArray[index] != not) { buffer.add(index); // buffer.add(InputArray[index]); // price } } this.base[i] = buffer.stream().mapToInt(Integer::intValue).toArray(); buffer.clear(); } start(length); } protected void dfs(int position) throws Exception { used[position] = true; quantity++; int next; boolean findKnot = Main.knot == null; if (base[position].length == 1) { findKnot = false; assert !Main.leafs.contains(position); Main.leafs.add(position + 1); } int[] leaf = new int[]{position + 1, -1, -1}; int i1 = 1; for (int index = 0; index < base[position].length; index++) { next = base[position][index]; if (!used[next]) { if (findKnot) { if (i1 < 2) { leaf[i1++] = next + 1; } } if (base[next].length != 1) { findKnot = false; } ancestor[next] = position; dfs(next); } /*else { if (next != ancestor[position]) { // if cycle throw new Exception(); } }*/ } if (findKnot) { leaf[2] = ancestor[position]; Main.knot = leaf.clone(); } } protected int dijkstra(int start, int stop, int size) { start--; stop--; int[] dist = new int[size]; for (int i = 0; i < size; i++) { if (i != start) { dist[i] = Integer.MAX_VALUE; } ancestor[i] = start; } Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt((int[] ints) -> ints[1])); queue.add(new int[]{start, 0}); int position; int[] getQueue; while (queue.size() != 0) { getQueue = queue.poll(); position = getQueue[0]; if (getQueue[1] > dist[position]) { continue; } for (int index = 0; index < this.base[position].length; index += 2) { if (dist[position] + this.base[position][index + 1] < dist[this.base[position][index]] && !this.used[this.base[position][index]]) { dist[this.base[position][index]] = dist[position] + this.base[position][index + 1]; this.ancestor[this.base[position][index]] = position; queue.add(new int[]{this.base[position][index], dist[this.base[position][index]]}); } } used[position] = true; } return dist[stop] == Integer.MAX_VALUE ? -1 : dist[stop]; } protected static boolean solveFloydWarshall(int[][] base, int length, int not) { for (int k = 0; k < length; k++) { for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (base[i][k] == not || base[k][j] == not) { continue; } int total = base[i][k] + base[k][j]; if (base[i][j] != not) { base[i][j] = Math.min(base[i][j], total); } else { base[i][j] = total; } } } } for (int index = 0; index < length; index++) { if (base[index][index] != 0) { // if cycle return false; } } return true; } protected static Pair<Long, int[][]> solveKruskal(int[][] edgesMatrix, final int countVertex, final int indexSort) { int[][] answer = new int[countVertex - 1][2]; long sum = 0; Arrays.sort(edgesMatrix, Comparator.comparingInt(value -> value[indexSort])); SystemOfDisjointSets dsu = new SystemOfDisjointSets(countVertex); for (int i = 0; i < countVertex; i++) { dsu.makeSet(i); } int index = 0; for (int[] value : edgesMatrix) { if (dsu.mergeSets(value[0], value[1])) { sum += value[indexSort]; answer[index] = new int[]{value[0], value[1]}; index++; } } if (index < countVertex - 1) { return Pair.createPair(null, null); } return Pair.createPair(sum, answer); } static class SegmentTree { private int[] segmentArray; private BiFunction<Integer, Integer, Integer> function; protected void setSegmentArray(int[] segmentArray) { this.segmentArray = segmentArray; } protected int[] getSegmentArray() { return segmentArray.clone(); } protected void setFunction(BiFunction<Integer, Integer, Integer> function) { this.function = function; } protected BiFunction<Integer, Integer, Integer> getFunction() { return function; } SegmentTree() { } SegmentTree(int[] startBase, int neutral, BiFunction<Integer, Integer, Integer> function) { this.function = function; int length = startBase.length; int[] base; if ((length & (length - 1)) != 0) { int pow = 0; while (length > 0) { length >>= 1; pow++; } pow--; base = new int[2 << pow]; System.arraycopy(startBase, 0, base, 0, startBase.length); Arrays.fill(base, startBase.length, base.length, neutral); } else { base = startBase; } segmentArray = new int[base.length << 1]; // maybe * 4 Arrays.fill(segmentArray, neutral); inDepth(base, 1, 0, base.length - 1); } private void inDepth(int[] base, int position, int low, int high) { if (low == high) { segmentArray[position] = base[low]; } else { int mid = (low + high) >> 1; inDepth(base, position << 1, low, mid); inDepth(base, (position << 1) + 1, mid + 1, high); segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]); } } protected int getValue(int left, int right, int neutral) { return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral); } private int findValue(int position, int low, int high, int left, int right, int neutral) { if (left > right) { return neutral; } if (left == low && right == high) { return segmentArray[position]; } int mid = (low + high) >> 1; return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral), findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral)); } protected void replaceValue(int index, int value) { update(1, 0, (segmentArray.length >> 1) - 1, index, value); } private void update(int position, int low, int high, int index, int value) { if (low == high) { segmentArray[position] = value; } else { int mid = (low + high) >> 1; if (index <= mid) { update(position << 1, low, mid, index, value); } else { update((position << 1) + 1, mid + 1, high, index, value); } segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]); } } } static class SegmentTreeGeneric<T> { private Object[] segmentArray; private BiFunction<T, T, T> function; protected void setSegmentArray(T[] segmentArray) { this.segmentArray = segmentArray; } protected Object getSegmentArray() { return segmentArray.clone(); } protected void setFunction(BiFunction<T, T, T> function) { this.function = function; } protected BiFunction<T, T, T> getFunction() { return function; } SegmentTreeGeneric() { } SegmentTreeGeneric(T[] startBase, T neutral, BiFunction<T, T, T> function) { this.function = function; int length = startBase.length; Object[] base; if ((length & (length - 1)) != 0) { int pow = 0; while (length > 0) { length >>= 1; pow++; } pow--; base = new Object[2 << pow]; System.arraycopy(startBase, 0, base, 0, startBase.length); Arrays.fill(base, startBase.length, base.length, neutral); } else { base = startBase; } segmentArray = new Object[base.length << 1]; // maybe * 4 Arrays.fill(segmentArray, neutral); inDepth(base, 1, 0, base.length - 1); } private void inDepth(Object[] base, int position, int low, int high) { if (low == high) { segmentArray[position] = base[low]; } else { int mid = (low + high) >> 1; inDepth(base, position << 1, low, mid); inDepth(base, (position << 1) + 1, mid + 1, high); segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]); } } protected T getValue(int left, int right, T neutral) { return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral); } private T findValue(int position, int low, int high, int left, int right, T neutral) { if (left > right) { return neutral; } if (left == low && right == high) { return (T) segmentArray[position]; } int mid = (low + high) >> 1; return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral), findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral)); } protected void replaceValue(int index, T value) { update(1, 0, (segmentArray.length >> 1) - 1, index, value); } private void update(int position, int low, int high, int index, T value) { if (low == high) { segmentArray[position] = value; } else { int mid = (low + high) >> 1; if (index <= mid) { update(position << 1, low, mid, index, value); } else { update((position << 1) + 1, mid + 1, high, index, value); } segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]); } } } } class SystemOfDisjointSets { private int[] rank; private int[] ancestor; SystemOfDisjointSets(int size) { this.rank = new int[size]; this.ancestor = new int[size]; } protected void makeSet(int value) { ancestor[value] = value; rank[value] = 0; } protected int findSet(int value) { if (value == ancestor[value]) { return value; } return ancestor[value] = findSet(ancestor[value]); } protected boolean mergeSets(int first, int second) { first = findSet(first); second = findSet(second); if (first != second) { if (rank[first] < rank[second]) { int number = first; first = second; second = number; } ancestor[second] = first; if (rank[first] == rank[second]) { rank[first]++; } return true; } return false; } } interface Array { void useArray(int[] a); } interface Method { void use(); } class FastSort { protected static int[] sort(int[] array, int ShellHeapMergeMyInsertionSort) { sort(array, ShellHeapMergeMyInsertionSort, array.length); return array; } protected static int[] sortClone(int[] array, int ShellHeapMergeMyInsertionSort) { int[] base = array.clone(); sort(base, ShellHeapMergeMyInsertionSort, array.length); return base; } private static void sort(int[] array, int ShellHeapMergeMyInsertionSort, int length) { if (ShellHeapMergeMyInsertionSort < 0 || ShellHeapMergeMyInsertionSort > 4) { Random random = new Random(); ShellHeapMergeMyInsertionSort = random.nextInt(4); } if (ShellHeapMergeMyInsertionSort == 0) { ShellSort(array); } else if (ShellHeapMergeMyInsertionSort == 1) { HeapSort(array); } else if (ShellHeapMergeMyInsertionSort == 2) { MergeSort(array, 0, length - 1); } else if (ShellHeapMergeMyInsertionSort == 3) { straightMergeSort(array, length); } else if (ShellHeapMergeMyInsertionSort == 4) { insertionSort(array); } } private static void straightMergeSort(int[] array, int size) { if (size == 0) { return; } int length = (size >> 1) + ((size % 2) == 0 ? 0 : 1); Integer[][] ZeroBuffer = new Integer[length + length % 2][2]; Integer[][] FirstBuffer = new Integer[0][0]; for (int index = 0; index < length; index++) { int ArrayIndex = index << 1; int NextArrayIndex = (index << 1) + 1; if (NextArrayIndex < size) { if (array[ArrayIndex] > array[NextArrayIndex]) { ZeroBuffer[index][0] = array[NextArrayIndex]; ZeroBuffer[index][1] = array[ArrayIndex]; } else { ZeroBuffer[index][0] = array[ArrayIndex]; ZeroBuffer[index][1] = array[NextArrayIndex]; } } else { ZeroBuffer[index][0] = array[ArrayIndex]; } } boolean position = false; int pointer0, pointer, pointer1, number = 4, NewPointer, count; Integer[][] NewBuffer; Integer[][] OldBuffer; length = (size >> 2) + ((size % 4) == 0 ? 0 : 1); while (true) { pointer0 = 0; count = (number >> 1) - 1; if (!position) { FirstBuffer = new Integer[length + length % 2][number]; NewBuffer = FirstBuffer; OldBuffer = ZeroBuffer; } else { ZeroBuffer = new Integer[length + length % 2][number]; NewBuffer = ZeroBuffer; OldBuffer = FirstBuffer; } for (int i = 0; i < length; i++) { pointer = 0; pointer1 = 0; NewPointer = pointer0 + 1; if (length == 1) { for (int g = 0; g < size; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } array[g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { array[g] = OldBuffer[pointer0][pointer]; pointer++; } } return; } for (int g = 0; g < number; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { if (OldBuffer[NewPointer][pointer1] == null) { continue; } NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } } pointer0 += 2; } position = !position; length = (length >> 1) + length % 2; number <<= 1; } } private static void ShellSort(int[] array) { int j; for (int gap = (array.length >> 1); gap > 0; gap >>= 1) { for (int i = gap; i < array.length; i++) { int temp = array[i]; for (j = i; j >= gap && array[j - gap] > temp; j -= gap) { array[j] = array[j - gap]; } array[j] = temp; } } } private static void HeapSort(int[] array) { for (int i = (array.length >> 1) - 1; i >= 0; i--) shiftDown(array, i, array.length); for (int i = array.length - 1; i > 0; i--) { swap(array, 0, i); shiftDown(array, 0, i); } } private static void shiftDown(int[] array, int i, int n) { int child; int tmp; for (tmp = array[i]; leftChild(i) < n; i = child) { child = leftChild(i); if (child != n - 1 && (array[child] < array[child + 1])) child++; if (tmp < array[child]) array[i] = array[child]; else break; } array[i] = tmp; } private static int leftChild(int i) { return (i << 1) + 1; } private static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } private static void MergeSort(int[] array, int low, int high) { if (low < high) { int mid = (low + high) >> 1; MergeSort(array, low, mid); MergeSort(array, mid + 1, high); merge(array, low, mid, high); } } private static void merge(int[] array, int low, int mid, int high) { int n = high - low + 1; int[] Temp = new int[n]; int i = low, j = mid + 1; int k = 0; while (i <= mid || j <= high) { if (i > mid) Temp[k++] = array[j++]; else if (j > high) Temp[k++] = array[i++]; else if (array[i] < array[j]) Temp[k++] = array[i++]; else Temp[k++] = array[j++]; } for (j = 0; j < n; j++) array[low + j] = Temp[j]; } private static void insertionSort(int[] elements) { for (int i = 1; i < elements.length; i++) { int key = elements[i]; int j = i - 1; while (j >= 0 && key < elements[j]) { elements[j + 1] = elements[j]; j--; } elements[j + 1] = key; } } } class IO { private static BufferedReader read; private static boolean fileInput = false; private static BufferedWriter write; private static boolean fileOutput = false; public static void setFileInput(boolean fileInput) { IO.fileInput = fileInput; } public static void setFileOutput(boolean fileOutput) { IO.fileOutput = fileOutput; } private static void startInput() { try { read = new BufferedReader(fileInput ? new FileReader("input.txt") : new InputStreamReader(System.in)); } catch (Exception error) { } } private static void startOutput() { try { write = new BufferedWriter(fileOutput ? new FileWriter("output.txt") : new OutputStreamWriter(System.out)); } catch (Exception error) { } } protected static int readInt() throws Exception { if (read == null) { startInput(); } return Integer.parseInt(read.readLine()); } protected static long readLong() throws Exception { if (read == null) { startInput(); } return Long.parseLong(read.readLine()); } protected static String readString() throws Exception { if (read == null) { startInput(); } return read.readLine(); } protected static int[] readArrayInt(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToInt(Integer::parseInt).toArray(); } protected static long[] readArrayLong(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToLong(Long::parseLong).toArray(); } protected static String[] readArrayString(String split) throws Exception { if (read == null) { startInput(); } return read.readLine().split(split); } protected static void writeArray(int[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Integer[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Int[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index].value)); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(long[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Long[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } public static void writeArray(String[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(array[index]); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception ignored) { } } protected static void writeArray(boolean[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Boolean.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception ignored) { } } protected static void writeInt(int number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeInt(Integer number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeLong(long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeLong(Long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeString(String word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeBoolean(boolean value, String end) { if (write == null) { startOutput(); } try { write.write(value ? "true" : "false"); write.write(end); } catch (Exception ignored) { } } protected static void writeBoolean(Boolean value, String end) { if (write == null) { startOutput(); } try { write.write(value ? "true" : "false"); write.write(end); } catch (Exception ignored) { } } protected static void writeChar(char word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeChar(Character word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeEnter() { if (write == null) { startOutput(); } try { write.newLine(); } catch (Exception ignored) { } } protected static void print(boolean exit) throws Exception { if (exit) { print(); } else { write.flush(); } } protected static void print() throws Exception { if (write == null) { return; } write.flush(); if (read != null) { read.close(); } write.close(); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
bd93cb383d33864e29cc3213d15e9ec7
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.StringTokenizer; public class Solution{ static long mod = 998244353L; public static void main(String[] args) throws Exception{ FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = fs.nextInt(); int[][] adjList = new int[n-1][2]; int[] count = new int[n+1]; for(int i=0;i<n-1;i++) { int u = fs.nextInt(), v =fs.nextInt(); count[u]++; count[v]++; adjList[i][0] = u; adjList[i][1] = v; } int max = 1; for(int i=1;i<=n;i++) { if(count[i]>count[max]) max = i; } int n1 = 0; int n2 = count[max]; for(int i=0;i<n-1;i++) { if(adjList[i][0]==max || adjList[i][1]==max) { out.println(n1++); } else { out.println(n2++); } } out.close(); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
dc6e28d71702a1a95d03f6d9e647063d
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public int[] readArray(int n) throws Exception { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } } long mod1 = (long) 1e9 + 7; int mod2 = 998244353; public void solve() throws Exception { ArrayList<ArrayList<Integer>> a=new ArrayList<>(); int n=sc.nextInt(); for(int i=0;i<=n;i++) a.add(new ArrayList<>()); int arr[][]=new int[n][2]; int brr[]=new int[n-1]; Arrays.fill(brr, -1); int index=0; for(int i=0;i<n-1;i++) { arr[i][0]=sc.nextInt(); arr[i][1]=sc.nextInt(); a.get(arr[i][0]).add(arr[i][1]); a.get(arr[i][1]).add(arr[i][0]); } int count=0; for(int i=0;i<n-1;i++) { if(a.get(arr[i][0]).size()==1 || a.get(arr[i][1]).size()==1) { brr[i]=count; count++; } } for(int i=0;i<n-1;i++) { if(brr[i]==-1) { out.println(count+" "); count++; } else { out.println(brr[i]); } } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long ncr(int n, int r, long p) { if (r > n) return 0l; if (r > n - r) r = n - r; long C[] = new long[r + 1]; C[0] = 1; for (int i = 1; i <= n; i++) { for (int j = Math.min(i, r); j > 0; j--) C[j] = (C[j] + C[j - 1]) % p; } return C[r] % p; } public long power(long x, long y, long p) { long res = 1; // out.println(x+" "+y); x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
e5033f784e9858f35b605d45fd203de2
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author unknown */ 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); CEhabAndPathEticMEXs solver = new CEhabAndPathEticMEXs(); solver.solve(1, in, out); out.close(); } static class CEhabAndPathEticMEXs { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int childCount[] = new int[n + 1]; int edges[][] = new int[n - 1][2]; int values[] = new int[n - 1]; int markedValue = -1; for (int i = 0; i < n - 1; i++) { int u = in.nextInt(); int v = in.nextInt(); childCount[u] += 1; childCount[v] += 1; edges[i][0] = u; edges[i][1] = v; values[i] = -1; } for (int i = 0; i < n - 1; i++) { if (childCount[edges[i][0]] == 1 || childCount[edges[i][1]] == 1) { values[i] = ++markedValue; } } for (int i = 0; i < n - 1; i++) { if (values[i] == -1) { values[i] = ++markedValue; } } for (int i = 0; i < n - 1; i++) { out.println(values[i]); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
a0158f7bc717ee8055ababda37c7681e
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { Reader source; BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws Exception { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public void solve() throws Exception { int n = nextInt(); if (n == 2) { out.println(0); return; } ArrayList<Integer>[] g = new ArrayList [n + 1]; ArrayList<Integer>[] f = new ArrayList [n + 1]; boolean[] us = new boolean [n + 1]; int[] d = new int [n + 1]; int[] p = new int [n + 1]; int[] ans = new int [n + 1]; int a, b; for (int i = 0; i <= n; i++) { g[i] = new ArrayList<Integer>(); f[i] = new ArrayList<Integer>(); } for (int i = 1; i < n; i++) { a = nextInt(); b = nextInt(); g[a].add(b); f[a].add(i); g[b].add(a); f[b].add(i); } LinkedList<Integer> q = new LinkedList<Integer>(); for (int i = 1; i <= n; i++) { us[i] = false; d[i] = 1000000; } q.add(1); us[1] = true; d[1] = 0; while (!q.isEmpty()) { int v = q.poll(); for (int to : g[v]) { if (!us[to]) { us[to] = true; d[to] = d[v] + 1; q.push(to); } } } int L = 1; for (int i = 1; i <= n; i++) { if (d[i] > d[L]) L = i; } for (int i = 1; i <= n; i++) { us[i] = false; d[i] = 1000000; ans[i] = -1; } q.add(L); us[L] = true; d[L] = 0; while (!q.isEmpty()) { int v = q.poll(); for (int to : g[v]) { if (!us[to]) { us[to] = true; d[to] = d[v] + 1; p[to] = v; q.push(to); } } } int R = 1; for (int i = 1; i <= n; i++) { if (d[i] > d[R]) R = i; } for (int i = 0; i < g[R].size(); i++) { if (g[R].get(i) == p[R]) { ans[f[R].get(i)] = 0; R = g[R].get(i); break; } } int mx = n - 2; while (p[R] != L) { for (int i = 0; i < g[R].size(); i++) { if (g[R].get(i) == p[R]) { ans[f[R].get(i)] = mx--; R = g[R].get(i); break; } } } for (int i = 0; i < g[R].size(); i++) { if (g[R].get(i) == p[R]) { ans[f[R].get(i)] = 1; R = g[R].get(i); break; } } for (int i = 1; i < n; i++) { out.println(ans[i] != -1 ? ans[i] : mx--); } } public void run() throws Exception { source = OJ ? new InputStreamReader(System.in) : new FileReader("C.in"); br = new BufferedReader(source); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new C().run(); } private boolean OJ = System.getProperty("ONLINE_JUDGE") != null; }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
90a08d118f197af8f0121c4f1a0ca433
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; // Ashraf EzzEldin Mahmoud Teleb Taha Mohamed Soltan Saleemy Elkalaby // public class dsu { static ArrayList<Integer>[] adj; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); pair a[] = new pair[n - 1]; adj = new ArrayList[n]; for (int i = 0; i <adj.length; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < a.length; i++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); a[i] = new pair(x, y); adj[x - 1].add(y - 1); adj[y - 1].add(x - 1); } TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n-1; i++) { ts.add(i); } for (pair p : a) { if(adj[p.y-1].size()==1 ||adj[p.x-1].size()==1 ) { int x=ts.ceiling(0); pw.println(x); ts.remove(x); } else { int x=ts.floor(n+1); pw.println(x); ts.remove(x); } } pw.flush(); } // 0 // 3 // 4 // 5 // 1 // 2 static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static class pair implements Comparable<pair> { int x; int y; pair(int r, int t) { x = r; y = t; } public String toString() { return "(" + x + "," + y + ")"; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub return o.x - x; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
6873c7684e13931f108b75bf3a891155
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import javafx.util.Pair; public class Solve6 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve6().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); ArrayList<Pair<Integer, Integer>>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) { adj[i] = new ArrayList(); } for (int i = 0; i < n - 1; i++) { int x = sc.nextInt(), y = sc.nextInt(); adj[x].add(new Pair(y, i)); adj[y].add(new Pair(x, i)); } ans = new int[n - 1]; Arrays.fill(ans, -1); timer2 = n - 2; dfs(-1, 1, -1, adj); for (int i = 0; i < n - 1; i++) { pw.println(ans[i]); } } int[] ans; int timer, timer2; public void dfs(int p, int u, int j, ArrayList<Pair<Integer, Integer>>[] adj) { int child = 0; for (Pair<Integer, Integer> temp : adj[u]) { int v = temp.getKey(); if (v != p) { ++child; dfs(u, v, temp.getValue(), adj); } } if (child == 0) { ans[j] = timer++; } else if (p != -1) { ans[j] = timer2--; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { } } public String next() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception 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 String nextLine() { try { return br.readLine(); } catch (Exception e) { } return null; } public boolean hasNext() throws IOException { if (st != null && st.hasMoreTokens()) { return true; } String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
44b3d133609ea996a574676afe119cad
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.*; public class CF1325C { public static void main(String ...args) { Reader in = new Reader(); Writer out = new Writer(); int n = in.nextInt(); ArrayList<Pair<Integer, Integer>> edges = new ArrayList<>(); int[] degree = new int[n+1]; for(int i = 1;i<n;i++) { int u = in.nextInt(); int v = in.nextInt(); edges.add(new Pair<>(u,v)); degree[u]++; degree[v]++; } int small = 0; int large = n-2; int[] ans = new int[n-1]; for(int i = 0;i<n-1;i++) { Pair<Integer, Integer> edge = edges.get(i); if (degree[edge.getKey()] == 1 || degree[edge.getValue()] == 1) { ans[i] = small++; } else { ans[i] = large--; } } for(int i: ans) { out.println(i); } out.flush(); } } class Reader { private StringTokenizer a; private BufferedReader b; Reader () { a = null; try { b = new BufferedReader (new InputStreamReader (System.in)); // for file IO, replace this with new FileReader ("in.txt") } catch (Exception e) { e.printStackTrace(); } } public String next () { while(a == null || !a.hasMoreTokens()) { try { a = new StringTokenizer (b.readLine()); } catch (IOException e) { e.printStackTrace(); } } return a.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } public long nextLong () { return Long.parseLong(this.next()); } public double nextDouble () { return Double.parseDouble(this.next()); } public String nextLine() { try { return b.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } } class Writer { private PrintWriter a; private StringBuffer b; Writer () { try { a = new PrintWriter (System.out); // for file IO, replace this with new FileWriter ("out.txt") } catch (Exception e) { e.printStackTrace(); } b = new StringBuffer (""); } public void print (Object s) { b.append(s); } public void println(Object s) { b.append(s).append('\n'); } public void flush () { a.print(b); a.flush(); a.close(); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
4ce0437a43c4e9805a175cfd71834893
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class CF1325C { public static void main(String ...args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); ArrayList<Pair<Integer, Integer>> edges = new ArrayList<>(); int[] degree = new int[n+1]; for(int i = 1;i<n;i++) { String [] input = in.readLine().split(" "); int u = Integer.parseInt(input[0]); int v =Integer.parseInt(input[1]); edges.add(new Pair<>(u,v)); degree[u]++; degree[v]++; } int small = 0; int large = n-2; int[] ans = new int[n-1]; for(int i = 0;i<n-1;i++) { Pair<Integer, Integer> edge = edges.get(i); if (degree[edge.getKey()] == 1 || degree[edge.getValue()] == 1) { ans[i] = small++; } else { ans[i] = large--; } } for(int i: ans) { System.out.println(i); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
9d7f9f2bd0b833845ae93f5cb628282b
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Template { public static void solve(int testCase, Reader in, PrintWriter out){ int n = in.nextInt(); ArrayList<Pair<Integer, Integer>> edges = new ArrayList<>(); int[] degree = new int[n+1]; for(int i = 1;i<n;i++) { int u = in.nextInt(); int v = in.nextInt(); edges.add(new Pair<>(u,v)); degree[u]++; degree[v]++; } int small = 0; int large = n-2; int[] ans = new int[n-1]; for(int i = 0;i<n-1;i++) { Pair<Integer, Integer> edge = edges.get(i); if (degree[edge.getKey()] == 1 || degree[edge.getValue()] == 1) { ans[i] = small++; } else { ans[i] = large--; } } for(int i: ans) { out.println(i); } } public static void main(String... args) { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); int testCase = 1; for(int i = 1;i<=testCase;i++) { solve(i, in, out); } out.flush(); out.close(); } static class Reader { private StringTokenizer tokenizer; private BufferedReader reader; public Reader() { tokenizer = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); // for file IO, replace this with new FileReader ("in.txt") } catch (Exception e) { e.printStackTrace(); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } public long nextLong() { return Long.parseLong(this.next()); } public double nextDouble() { return Double.parseDouble(this.next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
fa30f0475641e74e4be77e6a985adc54
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { static class Edge{ int a,b,label; public Edge(int a,int b){ this.a=a; this.b=b; label=-1; } } static class Graph{ int V,deg[],cnt=0; ArrayList<Edge> l[]; //TreeSet<Integer> set=new TreeSet<Integer>(); ArrayList<Edge> li = new ArrayList<>(); public Graph(int v){ V=v; deg=new int[V+1]; l=new ArrayList[V+1]; for(int i=1;i<=V;i++){ l[i]=new ArrayList<Edge>(); //set.add(i); } } void addEdge(int u,int v){ Edge ed=new Edge(u,v); l[u].add(ed); l[v].add(ed); li.add(ed); deg[u]++; deg[v]++; } void do_stuff(){ for(int i=1;i<=V;i++){ if(deg[i]<3) continue; for(int j=1;j<=3;j++){ Edge e=l[i].get(j-1); e.label=cnt++; } break; } //System.out.println("dfas"); for(Edge e : li){ //System.out.println(e.label); if(e.label!=-1){ pn(e.label); continue; } pn(cnt++); } } } public static void process()throws IOException { int n=ni(); Graph g=new Graph(n); for(int i=1;i<n;i++) g.addEdge(ni(),ni()); // System.out.println("ds"); g.do_stuff(); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; oj = System.getProperty("ONLINE_JUDGE") != null; if(!oj) sc=new AnotherReader(100); long s = System.currentTimeMillis(); int t=1; while(t-->0) process(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static boolean multipleTC=false; ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
8391b83db21ebd1c5ca4fd8cb71e6aac
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Edge{ int u , v, label; public Edge(int u, int v){ this.u = u; this.v = v; label = -1; } } public static void process()throws IOException { int n = ni(), deg[] = new int[n+1], cnt = 0; ArrayList<Edge> l[] = new ArrayList[n+1]; ArrayList<Edge> li = new ArrayList<>(); for(int i = 0 ; i <= n; i++) l[i] = new ArrayList<>(); for(int i = 1; i <= n-1; i++){ int u = ni(), v = ni(); Edge e = new Edge(u, v); li.add(e); l[u].add(e); l[v].add(e); deg[u]++; deg[v]++; } boolean taken[] = new boolean[n+1]; for(int i = 1; i <= n; i++){ if(deg[i] >= 3){ for(int j = 0; j < 3; j++){ Edge e = l[i].get(j); e.label = cnt; cnt++; } break; } } for(Edge e : li){ if(e.label == -1){ pn(cnt); cnt++; } else pn(e.label); } } static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new FastReader(); long s = System.currentTimeMillis(); int t=1; //t=ni(); while(t-->0) process(); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static int ni()throws IOException{return Integer.parseInt(sc.next());} static long nl()throws IOException{return Long.parseLong(sc.next());} static double nd()throws IOException{return Double.parseDouble(sc.next());} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static long mod=(long)1e9+7l; ///////////////////////////////////////////////////////////////////////////////////////////////////////// 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
5895c1d4a39214c013d7ec2d41cd4799
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; public class CF1325C extends PrintWriter { CF1325C() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1325C o = new CF1325C(); o.main(); o.flush(); } int[] h1, h2, h3, ans; boolean deg3(int u, int h) { if (h1[u] == 0) h1[u] = h; else if (h2[u] == 0) h2[u] = h; else { h3[u] = h; ans[h1[u]] = 0; ans[h2[u]] = 1; ans[h3[u]] = 2; return true; } return false; } void main() { int n = sc.nextInt(); h1 = new int[n]; h2 = new int[n]; h3 = new int[n]; ans = new int[n]; Arrays.fill(ans, -1); int k = 0; for (int h = 1; h < n; h++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; if (deg3(u, h) || deg3(v, h)) { k = 3; break; } } for (int h = 1; h < n; h++) { if (ans[h] == -1) ans[h] = k++; println(ans[h]); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
da588daacc792b5cc46510d8b8a9d309
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import javax.sound.sampled.Line; import java.io.*; import java.math.BigInteger; import java.util.*; public class A { public static void main(String[] args) throws Throwable { long time = System.currentTimeMillis(); Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); int[] deg = new int[n]; for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; deg[u]++; deg[v]++; adj[u].add(new Edge(i, v)); adj[v].add(new Edge(i, u)); } int maxDeg = deg[0], maxNode = 0; for (int i = 1; i < n; i++) if (deg[i] > maxDeg) { maxDeg = deg[i]; maxNode = i; } boolean[] vis = new boolean[n]; Queue<Integer> q = new LinkedList<>(); vis[maxNode] = true; q.add(maxNode); int nxt = 0; int[] ans = new int[n - 1]; while (!q.isEmpty()) { int u = q.poll(); for (Edge e : adj[u]) { int v = e.v; if (!vis[v]) { vis[v] = true; ans[e.idx] = nxt++; q.add(v); } } } for (int x : ans) pw.println(x); pw.close(); System.err.println((System.currentTimeMillis() - time) / 1000.0); } static int n; static ArrayList<Edge>[] adj; static class Edge { int idx, v; Edge(int idx, int v) { this.idx = idx; this.v = v; } } static class Scanner { StringTokenizer st; BufferedReader br; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String s) throws Throwable { br = new BufferedReader(new FileReader(new File(s))); } String next() throws Throwable { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Throwable { return Integer.parseInt(next()); } long nextLong() throws Throwable { return Long.parseLong(next()); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
06974bde3e9aca5d095acec1bf72a2fc
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static LinkedList<int[]>[]adj; public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); adj=new LinkedList[n]; for(int i=0;i<n;i++)adj[i]=new LinkedList<int[]>(); for(int i=0;i<n-1;i++) { int x=sc.nextInt()-1,y=sc.nextInt()-1; adj[x].add(new int[]{y,i});adj[y].add(new int[]{x,i}); } int max=0; for(int i=0;i<n;i++) { if(adj[i].size()>adj[max].size()) { max=i; } } int[]ans=new int[n-1]; Arrays.fill(ans, -1); int val=0; for(int []j:adj[max]) { ans[j[1]]=val++; } for(int i=0;i<n-1;i++) { if(ans[i]==-1) { ans[i]=val++; } } for(int i=0;i<n-1;i++) { pw.println(ans[i]); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
2c4affacefef21fdf241213ea7b8b6d7
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.*; import java.util.ArrayList; import java.util.HashSet; public class Solution { static int n; static ArrayList<Integer> tree[]; public static void main(String[] args) throws IOException { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int i,j; n=in.nextInt(); tree=new ArrayList[n]; ArrayList<Integer> list[]=new ArrayList[n]; for(i=0;i<n;i++) { tree[i] = new ArrayList<>(); list[i]=new ArrayList<>(); } for(i=0;i<n-1;i++){ int x=in.nextInt()-1; int y=in.nextInt()-1; tree[x].add(y); tree[y].add(x); list[x].add(i); list[y].add(i); } int f=0; int ans[]=new int[n-1]; HashSet<Integer> set=new HashSet<>(); for(i=0;i<n;i++){ if(tree[i].size()>2){ f=1; ans[list[i].get(0)]=0; ans[list[i].get(1)]=1; ans[list[i].get(2)]=2; set.add(list[i].get(0)); set.add(list[i].get(1)); set.add(list[i].get(2)); break; } } if(f==0){ for(i=0;i<n-1;i++) sb.append(i).append("\n"); } else{ int k=3; for(i=0;i<n-1;i++){ if(!set.contains(i)) ans[i]=k++; sb.append(ans[i]).append("\n"); } } System.out.print(sb); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
4d0ba81b91358ddb4b0e9aef25eb80ec
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { final int INF = 0x3f3f3f3f; BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; public C() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) { new C(); } private void solve() { int n = nextInt(); List<Set<Integer>> g = new ArrayList<>(n + 1); for (int i = 0; i <= n; i++) { g.add(new HashSet<>()); } for (int i = 1; i < n; i++) { int from = nextInt(); int to = nextInt(); g.get(from).add(i); g.get(to).add(i); } int ind = 0; int max = 0; for (int i = 1; i <= n; i++) { if (max < g.get(i).size()) { max = g.get(i).size(); ind = i; } } int cur = 0; int[] ans = new int[n]; Arrays.fill(ans, -1); for (Integer i : g.get(ind)) { ans[i] = cur++; } for (int i = 1; i < n; i++) { if (ans[i] == -1) ans[i] = cur++; outln(ans[i]); } } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public long[] nextLongArr(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } public int[] nextIntArr(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
dd6344915619409650d78de79146ba94
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
//package bfs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; //public class FastReader { //} 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; } } class Graph { int n; List<List<Integer>> adjList; boolean visited[]; int countNeighbours[],parent[]; Graph(int nodes) { n=nodes; visited = new boolean[n]; adjList = new ArrayList<>(n); countNeighbours = new int[n]; parent = new int[n]; Arrays.fill(parent,-1); for(int i=0;i<n;i++) { adjList.add(new ArrayList<>()); } } void printList() { for(int i=0;i<n;i++) { System.out.print(i); List<Integer> list = adjList.get(i); for(int node:list) { System.out.print("->"+node); } System.out.println(); } } int[] getNeighbours() { return countNeighbours; } void addEdge(int m,int n) { adjList.get(m).add(n); adjList.get(n).add(m); countNeighbours[m]++; countNeighbours[n]++; } int getRootNode() { int index=-1,max=0; for(int i=0;i<n;i++) { if(countNeighbours[i]>max) {index=i;max=countNeighbours[i];} } return index; } void dfs(int start,boolean isLeafNode[]) { visited[start]=true; //System.out.println(start+" "); List<Integer> adjNodes=adjList.get(start); boolean leafNode=true; for(int neighbour:adjNodes) { if(!visited[neighbour]) { parent[neighbour]=start; leafNode=false; dfs(neighbour,isLeafNode); } } if(leafNode) isLeafNode[start]=true; else isLeafNode[start]=false; //return; } } class Pair{ int x; int y; int wt; Pair(int i,int j){ x=i; y=j; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31*result + y; return result; } } public class Main { public static void main(String args[]) { FastReader sc = new FastReader(); int n = sc.nextInt(); Graph g = new Graph(n); HashMap<Pair,Integer> map = new HashMap<>(); Pair p[] = new Pair[n-1]; for(int i=0;i<n-1;i++) { int v1 = sc.nextInt()-1;int v2 = sc.nextInt()-1;g.addEdge(v1,v2); //map.put(new Pair(v1,v2),-1); p[i]=new Pair(v1,v2); } boolean leafNodes[] = new boolean[n]; int root=g.getRootNode(); g.dfs(root,leafNodes); //ArrayList<Integer> leaves = new ArrayList<>(); HashSet<Integer> leaves = new HashSet<>(); for(int i=0;i<n;i++) if(leafNodes[i]) {leaves.add(i);} int min=0; int curr=leaves.size(); for(int i=0;i<n-1;i++) { if(leaves.contains(p[i].x)||leaves.contains(p[i].y)) {System.out.println(min);min++;} else {System.out.println(curr);curr++;} } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
b33d890473edb106079e7d47e3382717
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList(); int[][] edges = new int[n - 1][2]; for (int i = 1; i < n; i++) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; adj[u].add(v); adj[v].add(u); edges[i - 1][0] = u; edges[i - 1][1] = v; } int root = 0; for (int i = 0; i < n; i++) if (adj[i].size() > adj[root].size()) root = i; if (adj[root].size() <= 2) { for (int i = 0; i < n - 1; i++) out.println(i); } else { int[] ans = new int[n - 1]; Arrays.fill(ans, -1); int curr = 0; for (int i = 0; i < n - 1; i++) if (edges[i][0] == root || edges[i][1] == root) ans[i] = curr++; for (int i = 0; i < n - 1; i++) if (ans[i] == -1) ans[i] = curr++; for (int x : ans) out.println(x); } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
79eca352c43ecca6e7a2ca2f6088d116
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
// Problem: C. Ehab and Path-etic MEXs // Contest: Codeforces - Codeforces Round #628 (Div. 2) // URL: http://codeforces.com/contest/1325/problem/C // Memory Limit: 256 MB // Time Limit: 1000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE; static class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } } static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ if(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private long nextLong()throws IOException{ next(); return Long.parseLong(tk.nextToken()); } private String readString()throws IOException{ next(); return tk.nextToken(); } private double nextDouble()throws IOException{ next(); return Double.parseDouble(tk.nextToken()); } private int[] intArray(int n)throws IOException{ next(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } private long[] longArray(int n)throws IOException{ next(); long arr[] = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } } public static void main(String args[])throws IOException{ int t = 1; while(t-->0) solve(); pw.flush(); pw.close(); } private static void solve()throws IOException{ int n = sc.nextInt(); ArrayList<ArrayList<Pair>> tree = new ArrayList<>(); for(int i=0; i<n; i++) tree.add(new ArrayList<>()); int res[] = new int[n-1]; for(int i=0; i<n-1; i++){ res[i] = -1; int u = sc.nextInt() - 1, v = sc.nextInt() - 1; tree.get(u).add(new Pair(v, i)); tree.get(v).add(new Pair(u, i)); } boolean w = false; for(int i=0; i<n; i++){ if(tree.get(i).size() > 2){ for(int t=0; t<3; t++){ int j = tree.get(i).get(t).first, ind = tree.get(i).get(t).second; res[ind] = t; } w = true; break; } } int q = w ? 3 : 0; for(int i=0; i<n; i++){ for(Pair p : tree.get(i)){ int j = p.first, ind = p.second; if(res[ind] == -1) res[ind] = q++; } } for(int p: res) pw.println(+p); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
e5a0b23d5563303cd577dcd59f36a07e
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1325c { static Map<Long, Integer> ind = new HashMap<>(); static int lbl = 0, ans[]; public static void main(String[] args) throws IOException { int n = ri(); List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) { g.add(new ArrayList<>()); } int deg3 = -1; for(int i = 0; i < n - 1; ++i) { int a = rni() - 1, b = ni() - 1; g.get(a).add(b); g.get(b).add(a); if(g.get(a).size() == 3) { deg3 = a; } if(g.get(b).size() == 3) { deg3 = b; } ind.put(min(a, b) + (long)max(a, b) * 100000, i); } ans = new int[n - 1]; if(deg3 == -1) { for(int i = 0; i < n - 1; ++i) { ans[i] = i; } } else { fill(ans, - 1); for(int nn : g.get(deg3)) { // prln(deg3, nn.i); // flush(); ans[ind.get(min(nn, deg3) + (long)max(nn, deg3) * 100000)] = lbl++; } for(int i = 0; i < n - 1; ++i) { if(ans[i] == -1) { ans[i] = lbl++; } } } for(int i : ans) { prln(i); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void sort(int[] a) {shuffle(a); Arrays.sort(a);} static void sort(long[] a) {shuffle(a); Arrays.sort(a);} static void sort(double[] a) {shuffle(a); Arrays.sort(a);} static void qsort(int[] a) {Arrays.sort(a);} static void qsort(long[] a) {Arrays.sort(a);} static void qsort(double[] a) {Arrays.sort(a);} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output