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
b2a5a2025bfba073d76fa51c7df41284
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; public class Main{ static PrintWriter out; static InputReader ir; static final String[] s={"a","b","c"}; static void solve(){ int n=ir.nextInt(); int m=ir.nextInt(); G g=new G(n,true); boolean[][] es=new boolean[n][n]; for(int i=0;i<m;i++){ int u=ir.nextInt()-1; int v=ir.nextInt()-1; es[u][v]=es[v][u]=true; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(!es[i][j]) g.addEdge(i,j); } } int[] col=new int[n]; for(int i=0;i<n;i++){ if(g.size(i)!=0&&col[i]==0){ if(!dfs(i,1,g,col)){ out.println("No"); return; } } } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(es[i][j]&&col[i]*col[j]==-1){ out.println("No"); return; } } } out.println("Yes"); for(int i=0;i<n;i++) out.print(s[col[i]+1]); out.println(); } public static boolean dfs(int v,int c,G g,int[] col){ col[v]=c; for(int i=0;i<g.size(v);i++){ int to=g.to(v,i); if(col[to]==c) return false; if(col[to]==0&&!dfs(to,-c,g,col)) return false; } return true; } static class G{ AL[] g,rg; private int V; private boolean ndir; public G(int V,boolean ndir){ this.V=V; this.ndir=ndir; g=new AL[V]; for(int i=0;i<V;i++) g[i]=new AL(); } public void addEdge(int u,int v,int t){ g[u].add(new int[]{v,t}); if(this.ndir) g[v].add(new int[]{u,t}); } public void addEdge(int u,int v){ addEdge(u,v,0); } public int to(int from,int ind){return g[from].get(ind)[0];} public int cost(int from,int ind){return g[from].get(ind)[1];} public int size(int from){return g[from].size();} public int[] dijkstra(int s){ int[] dist=new int[this.V]; java.util.PriorityQueue<int[]> pque=new java.util.PriorityQueue<int[]>(11,new Comparator<int[]>(){ public int compare(int[] a,int[] b){ return Integer.compare(a[0],b[0]); } }); Arrays.fill(dist,1<<26); dist[s]=0; pque.offer(new int[]{0,s}); while(!pque.isEmpty()){ int[] p=pque.poll(); int v=p[1]; if(dist[v]<p[0]) continue; for(int i=0;i<g[v].size();i++){ int to=to(v,i),cost=cost(v,i); if(dist[to]>dist[v]+cost){ dist[to]=dist[v]+cost; pque.offer(new int[]{dist[to],to}); } } } return dist; } public int[] tporder(){ boolean[] vis=new boolean[V]; ArrayList<Integer> ord=new ArrayList<>(); for(int i=0;i<V;i++) if(!vis[i]) ts(i,vis,ord); int[] ret=new int[V]; for(int i=ord.size()-1;i>=0;i--) ret[ord.size()-1-i]=ord.get(i); return ret; } public int[] scc(){ rg=new AL[V]; for(int i=0;i<V;i++) rg[i]=new AL(); int from,to; for(int i=0;i<V;i++){ for(int j=0;j<g[i].size();j++){ to=i; from=to(i,j); rg[from].add(new int[]{to,0}); } } int[] ord=tporder(); int k=0; boolean[] vis=new boolean[V]; int[] ret=new int[V+1]; for(int i=0;i<V;i++) if(!vis[i]) rs(ord[i],vis,ret,k++); ret[V]=k; return ret; } private void ts(int now,boolean[] vis,ArrayList<Integer> ord){ vis[now]=true; int to; for(int i=0;i<g[now].size();i++){ to=to(now,i); if(!vis[to]) ts(to,vis,ord); } ord.add(now); } private void rs(int now,boolean[] vis,int[] ret,int k){ vis[now]=true; ret[now]=k; int to; for(int i=0;i<rg[now].size();i++){ to=rg[now].get(i)[0]; if(!vis[to]) rs(to,vis,ret,k); } } static class AL extends ArrayList<int[]>{}; } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public int[] nextIntArray(int n){ int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n){ long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
59a0a52958a4cd031c9293b5746a16fe
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AlexFetisov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA_ATM_1 solver = new TaskA_ATM_1(); solver.solve(1, in, out); out.close(); } static class TaskA_ATM_1 { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; g[a][b] = g[b][a] = true; } for (int i = 0; i < n; ++i) { g[i][i] = true; } int[] res = new int[n]; Arrays.fill(res, -1); for (int i = 0; i < n; ++i) { boolean isB = true; for (int j = 0; j < n; ++j) { if (!g[i][j]) { isB = false; break; } } if (isB) { res[i] = 1; } } boolean[] u = new boolean[n]; for (int i = 0; i < n; ++i) { if (res[i] == -1) { dfs(i, g, u, res); break; } } for (int i = 0; i < n; ++i) { if (res[i] != -1) continue; if (u[i]) { for (int j = 0; j < n; ++j) { if (res[j] == -1) { if (g[i][j] && !u[j]) { out.println("No"); return; } if (!g[i][j] && u[j]) { out.println("No"); return; } } } } else { for (int j = 0; j < n; ++j) { if (res[j] == -1) { if (g[i][j] && u[j]) { out.println("No"); return; } if (!g[i][j] && !u[j]) { out.println("No"); return; } } } } } for (int i = 0; i < n; ++i) { if (u[i]) { res[i] = 0; } } out.println("Yes"); for (int c : res) { if (c == 0) { out.print('a'); } else if (c == 1) { out.print('b'); } else { out.print('c'); } } out.println(); } private void dfs(int v, boolean[][] g, boolean[] u, int[] a) { u[v] = true; for (int i = 0; i < g.length; ++i) { if (g[v][i] && !u[i] && a[i] == -1) { dfs(i, g, u, a); } } } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
d4615d8a92a1723bd1cc3cd67d6cfaf2
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; public class Main { public static void main(String[] args) throws NumberFormatException, IOException {Solve solve = new Solve();solve.solve();} } class Solve{ void dump(int[]a){for(int i=0;i<a.length;i++) System.out.print(a[i]+" ");System.out.println();}; void dump(int[]a,int n){for(int i=0;i<a.length;i++) System.out.printf("%"+n+"d",a[i]);System.out.println();}; void solve() throws NumberFormatException, IOException{ ContestScanner in = new ContestScanner(); Writer out = new Writer(); int n = in.nextInt(); int m = in.nextInt(); if(m == n*(n-1)/2){ System.out.println("Yes"); for(int i=0; i<n; i++) out.append('a'); out.println(); out.close(); } Node[] node = new Node[n]; for(int i=0; i<n; i++) node[i] = new Node(i); for(int i=0; i<m; i++){ int u = in.nextInt()-1; int v = in.nextInt()-1; node[u].append(node[v]); node[v].append(node[u]); } char[] code = new char[n]; int check = 0; for(int i=0; i<n; i++){ if(node[i].cnt!=n-1) continue; code[i] = 'b'; check++; for(Node v: node[i].edge){ v.remove(node[i]); } } for(int i=0; i<n; i++){ if(code[i]!=0) continue; if(!isCompleteGraph(node[i], n)){ System.out.println("No"); return; } code[i] = 'a'; check++; for(Node v: node[i].edge){ code[v.id] = 'a'; check++; } break; } for(int i=0; i<n; i++){ if(code[i]!=0) continue; if(!isCompleteGraph(node[i], n)){ System.out.println("No"); return; } code[i] = 'c'; check++; for(Node v: node[i].edge){ code[v.id] = 'c'; check++; } break; } for(int i=0; i<n; i++){ if(code[i]==0){ System.out.println("No"); return; } } if(check==n){ System.out.println("Yes"); for(int i=0; i<n; i++){ out.write(code[i]); } out.println(); out.close(); }else System.out.println("No"); } boolean isCompleteGraph(Node s, int n){ BitSet used = new BitSet(n); BitSet tmp = new BitSet(n); for(Node v: s.edge){ used.set(v.id); } used.set(s.id); for(Node v: s.edge){ tmp.clear(); tmp.set(v.id); for(Node vv: v.edge){ tmp.set(vv.id); } if(!tmp.equals(used)) return false; } return true; } } class Node{ int id, cnt; HashSet<Node> edge = new HashSet<>(); Node(int id){this.id = id;} void append(Node v){ edge.add(v); cnt++; } void remove(Node v){ edge.remove(v); } } class MultiSet<T> extends HashMap<T, Integer>{ @Override public Integer get(Object key){return containsKey(key)?super.get(key):0;} public void add(T key,int v){put(key,get(key)+v);} public void add(T key){put(key,get(key)+1);} public void sub(T key){ final int num = get(key); if(num==1) remove(key); else put(key, num-1); } } class Writer extends PrintWriter{ public Writer(String filename) throws IOException {super(new BufferedWriter(new FileWriter(filename)));} public Writer() throws IOException{super(System.out);} } class ContestScanner { private InputStreamReader reader;int c=-2; public ContestScanner() throws IOException {reader = new InputStreamReader(System.in);} public ContestScanner(String filename) throws IOException {reader = new InputStreamReader(new FileInputStream(filename));} public String nextToken() throws IOException { StringBuilder sb = new StringBuilder();if(c==-2) c=reader.read(); while(c!=-1&&(c==' '||c=='\t'||c=='\n'||c=='\r'))c=reader.read(); while(c!=-1&&c!=' '&&c!='\t'&&c!='\n'&&c!='\r'){sb.appendCodePoint(c);c=reader.read();} return sb.toString(); } public String readLine() throws IOException{ StringBuilder sb = new StringBuilder();if(c==-2)c=reader.read(); while(c!=-1&&c!='\n'&&c!='\r'){sb.appendCodePoint(c);c=reader.read();} return sb.toString(); } public long nextLong() throws IOException, NumberFormatException {return Long.parseLong(nextToken());} public int nextInt() throws NumberFormatException, IOException {return (int) nextLong();} public double nextDouble() throws NumberFormatException, IOException {return Double.parseDouble(nextToken());} }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
eb4b9a56aff73f3ee4a4685e11c139dc
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class C { static ArrayList<ArrayList<Integer>> g; static int[] str; static boolean correct = true; static String toChar(int i) { switch(i) { case 0 : return "a"; case 1 : return "b"; case 2 : return "c"; } return "a"; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(), m = in.nextInt(); str = new int[n]; Arrays.fill(str, -1); g = new ArrayList<>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; g.get(u).add(v); g.get(v).add(u); } for (int i = 0; i < n; i++) { if (g.get(i).size() == n - 1) str[i] = 1; } for (int i = 0; i < n; i++) { if (str[i] == 1) continue; for (Integer ver : g.get(i)) { if (str[ver] == 1 || str[ver] == -1) continue; if (str[i] == -1) { str[i] = str[ver] == 0 ? 0 : 2; } else { if (str[i] != str[ver]) correct = false; } } for (int ver = 0; ver < n; ver++) { if (ver == i) continue; if (g.get(i).contains(ver) || str[ver] == -1) continue; if (str[ver] == 1) correct = false; if (str[i] == -1) { str[i] = str[ver] == 0 ? 2 : 0; } else { if (str[i] == str[ver]) correct = false; } } if (str[i] == -1) str[i] = 0; for (Integer ver : g.get(i)) { if (str[ver] == -1) str[ver] = str[i] == 0 ? 0 : 2; } for (int ver = 0; ver < n; ver++) { if (ver == i) continue; if (!g.get(i).contains(ver) && str[ver] == -1) { str[ver] = str[i] == 0 ? 2 : 0; } } } if (!correct) { out.println("No"); } else { out.println("Yes"); for (int i = 0; i < n; i++) { out.print(str[i] == -1 ? "a" : toChar(str[i])); } out.println(); } in.close(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } public Scanner(File source) throws IOException { br = new BufferedReader(new FileReader(source)); st = new StringTokenizer(br.readLine()); } public int nextInt() throws IOException { while (!st.hasMoreTokens()) { String s = br.readLine(); if (s == null) throw new IOException("No more ints"); st = new StringTokenizer(s); } return Integer.parseInt(st.nextToken()); } public String next() throws IOException { while (!st.hasMoreTokens()) { String s = br.readLine(); if (s == null) throw new IOException("No more ints"); st = new StringTokenizer(s); } return st.nextToken(); } public boolean hasNext() throws IOException { while (!st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return false; st = new StringTokenizer(s); } return true; } public void close() throws IOException { br.close(); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
f2f5ed05dc96925de2d2efae8504d4ed
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); n = in.nextInt(); int m = in.nextInt(); graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } s = new char[n]; Arrays.fill(s, 'x'); for (int i = 0; i < n; i++) { boolean found = false; for (int j = 0; j < n; j++) if (i != j && !graph[i][j]) { found = true; break; } if (!found) s[i] = 'b'; } for (int i = 0; i < n; i++) if (s[i] == 'x') { s[i] = 'a'; for (int j = 0; j < n; j++) if (s[j] == 'x') { if (graph[i][j]) s[j] = 'a'; else s[j] = 'c'; } } boolean ok = true; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i != j) { int d = Math.abs(s[i] - s[j]); if (d <= 1 && !graph[i][j]) ok = false; if (d == 2 && graph[i][j]) ok = false; } if (ok) out.printf("Yes\n%s\n", String.valueOf(s)); else out.println("No"); } private static int n; private static boolean[][] graph; private static char[] s; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
9b6919103c3c6bd632ae9913334da421
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main{ static boolean[][] adjMat; static ArrayList<Integer>[] adjList; static int[] color; static boolean bipartitieCheck(int u) { for(int v: adjList[u]) if(color[v] == -1) { color[v] = 1 ^ color[u]; if(!bipartitieCheck(v)) return false; } else if(color[v] == color[u]) return false; return true; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st= new StringTokenizer(bf.readLine()); int n= Integer.parseInt(st.nextToken()); int e= Integer.parseInt(st.nextToken()); adjList= new ArrayList [n] ; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<Integer>(); } color= new int[n]; Arrays.fill(color, -1); adjMat= new boolean [n][n] ; for (int i = 0; i <e; i++) { st= new StringTokenizer(bf.readLine()); int u= Integer.parseInt(st.nextToken()); int v= Integer.parseInt(st.nextToken()); adjMat[u-1][v-1]=true; adjMat[v-1][u-1]=true; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) if(i!=j){ if (!adjMat[i][j]){ adjList[i].add(j); adjList[j].add(i); } } } for (int i = 0; i < n; i++) { if (adjList[i].size()==0) color[i]=2; } boolean b=true;; for (int i = 0; i < n; i++) { if (adjList[i].size()!=0) if(color[i]!=2){ if(color[i]==-1){ color[i]=1;} b=bipartitieCheck(i); if(!b){ break; } } } if(!b){ System.out.println("No"); }else { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if(i!=j){ if(color[i]==color[j] && !adjMat[i][j]){ System.out.println("No"); return;} if(color[i]==(color[j]^1) && adjMat[i][j]){ System.out.println("No"); return;}} } } String res=""; for (int i = 0; i < color.length; i++) { if(color[i]==0){ res+="c"; }else if(color[i]==1){ res+="a"; }else { res+="b"; } } System.out.println("Yes"); System.out.println(res); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
b0d591c6efd271bb0ba1b469f5a44d3f
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author Sourav Kumar Paul */ public class SolveC { public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); boolean mat[][] = new boolean[n][n]; int edge[] = new int[n]; for(int i=0; i<m; i++) { st = new StringTokenizer(reader.readLine()); int x = Integer.parseInt(st.nextToken())-1; int y = Integer.parseInt(st.nextToken())-1; mat[x][y] = true; mat[y][x] = true; edge[x]++; edge[y]++; } char ans[] = new char[n]; Arrays.fill(ans, 'z'); for(int i=0; i<n; i++) { if(edge[i] == n-1) ans[i] = 'b'; } for(int i=0; i<n; i++) { if(ans[i] == 'z') { ans[i] = 'a'; for(int j=0; j<n; j++) { if(ans[j] == 'z') { if(!mat[i][j]) ans[j] = 'c'; else ans[j] = 'a'; } } } } for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(i==j) continue; if(Math.abs(ans[i] -ans[j]) <2 && !mat[i][j] || Math.abs(ans[i] - ans[j]) == 2 && mat[i][j]) { System.out.println("No"); return; } } } System.out.println("Yes"); for(int i=0; i<ans.length; i++) System.out.print(ans[i]); //System.out.println(ans.toString()); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
53c9841024d570da6ccf86ef46b85512
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class CF_624C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), m = scan.nextInt(); int[] degrees = new int[n]; ArrayList<Integer>[] edgeLists = new ArrayList[n]; for(int i=0;i<n;i++) edgeLists[i] = new ArrayList<>(); for(int i=0;i<m;i++) { int a = scan.nextInt()-1, b = scan.nextInt()-1; edgeLists[a].add(b); edgeLists[b].add(a); degrees[a]++; degrees[b]++; } char[] string = new char[n]; Arrays.fill(string, '\0'); for(int i=0;i<n;i++) { if(degrees[i] == n-1) string[i] = 'b'; } int countA = -1; int countC = -1; for(int i=0;i<n;i++) { char type = string[i]; if(type == 'b') continue; if(type == 'a' || type == 'c') { int count = 0; for(int edge : edgeLists[i]) { if(string[edge] == 'b') continue; if(string[edge] != type) { System.out.println("No"); System.err.println(type + " connects to " + string[edge]); return; } count++; } boolean works = type == 'a' ? countA==count : countC==count; if(!works) { System.out.println("No"); System.err.println(type + " hits " + count + ", should hit more"); return; } continue; } char newType; if(countA == -1) { newType = 'a'; } else if(countC == -1) { newType = 'c'; } else { System.out.println("No"); System.err.println("Used all available letters"); return; } string[i] = newType; int count = 0; for(int edge : edgeLists[i]) { if(string[edge] == 'b') continue; if(string[edge] != type) { System.out.println("No"); System.err.println("New empty letter is attached to an old letter"); return; } string[edge] = newType; count++; } if(newType == 'a') { countA = count; } else if(newType == 'c') { countC = count; } } System.out.println("Yes"); System.out.println(new String(string)); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
9fdd3d4dabe2a33537eeae33f29e0588
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static int V; static int[] s; static boolean[][] adjMat; static boolean color(int u, int c) { s[u] = c; for(int v = 0; v < V; ++v) if(u != v && !adjMat[u][v]) { if(s[v] == -1) { if(!color(v, c ^ 1)) return false; } else if(s[v] == s[u]) return false; } return true; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); V = sc.nextInt(); int E = sc.nextInt(); s = new int[V]; Arrays.fill(s, -1); adjMat = new boolean[V][V]; int[] deg = new int[V]; while(E-->0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; adjMat[u][v] = adjMat[v][u] = true; deg[u]++; deg[v]++; } boolean possible = true; for(int i = 0; possible && i < V; ++i) if(s[i] == -1 && deg[i] != V - 1) possible &= color(i, 1); for(int i = 0; possible && i < V; ++i) for(int j = 0; j < V; ++j) if(adjMat[i][j] && s[i] + s[j] == 1) possible = false; if(!possible) out.println("No"); else { out.println("Yes"); StringBuilder ans = new StringBuilder(); for(int i = 0; i < V; ++i) if(s[i] == -1) ans.append('b'); else if(s[i] == 0) ans.append('a'); else ans.append('c'); out.println(ans); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
fdbe11b22360a64ccaa3f081ed20b8d3
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.*; public class Main { int N,M; int[] kind; boolean[][] connect; public void solve(){ N = nextInt(); M = nextInt(); connect = new boolean[N][N]; for(int i = 0;i < M;i++){ int u = nextInt() - 1; int v = nextInt() - 1; connect[u][v] = connect[v][u] = true; } kind = new int[N]; Arrays.fill(kind,1); for(int i = 0;i < N;i++){ for(int j = i + 1;j < N;j++){ if(!connect[i][j]){ if(kind[i] == 1){ kind[i] = 0; kind[j] = 2; }else if(kind[i] == 0){ kind[j] = 2; }else{ kind[j] = 0; } } } } for(int i = 0;i < N;i++){ for(int j = i + 1;j < N;j++){ if(!connect[i][j] && Math.abs(kind[i] - kind[j]) <= 1){ out.println("No"); return; } if(connect[i][j] && Math.abs(kind[i] - kind[j]) >= 2){ out.println("No"); return ; } } } out.println("Yes"); for(int i = 0;i < N;i++){ out.print((char)(kind[i] + 'a')); } out.println(); } public static void main(String[] args) { out.flush(); new Main().solve(); out.close(); } /* Input */ private static final InputStream in = System.in; private static final PrintWriter out = new PrintWriter(System.out); private final byte[] buffer = new byte[2048]; private int p = 0; private int buflen = 0; private boolean hasNextByte() { if (p < buflen) return true; p = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } public boolean hasNext() { while (hasNextByte() && !isPrint(buffer[p])) { p++; } return hasNextByte(); } private boolean isPrint(int ch) { if (ch >= '!' && ch <= '~') return true; return false; } private int nextByte() { if (!hasNextByte()) return -1; return buffer[p++]; } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = -1; while (isPrint((b = nextByte()))) { sb.appendCodePoint(b); } return sb.toString(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
5f3dbd61eb49f38086752b3774e3874c
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.*; import java.util.*; public class Main { private final static InputReader ir = new InputReader(System.in); private final static PrintWriter ow = new PrintWriter(System.out); static int n; static char[] ans; static ArrayList<LinkedList<Integer>> graph; static void dfs(boolean[] used, int v) { used[v] = true; graph.get(v).stream().filter(u -> !used[u]).forEach(u -> dfs(used, u)); } static boolean checkB(int v) { boolean[] used = new boolean[n]; used[v] = true; graph.get(v).forEach(u -> used[u] = true); for (int i = 0; i < n; ++i) { if (!used[i]) { return false; } } return true; } public static void main(String[] args) throws IOException { n = ir.ni(); ans = new char[n]; for (int i = 0; i < n; ++i) { ans[i] = '*'; } graph = new ArrayList<>(n); int m = ir.ni(); for (int i = 0; i < n; ++i) { graph.add(new LinkedList<>()); } for (int i = 0; i < m; ++i) { int u = ir.ni() - 1; int v = ir.ni() - 1; graph.get(u).add(v); graph.get(v).add(u); } for (int i = 0; i < n; ++i) { if(checkB(i)) { ans[i] = 'b'; } } for (int i = 0; i < n; ++i) { if (ans[i] != 'b') { boolean[] used = new boolean[n]; used[i] = true; for (int v: graph.get(i)) { used[v] = true; } char mark = '*'; for (int j = 0; j < n; ++j) { if (!used[j]) { if (mark == '*') { mark = ans[j]; } else { if (mark != ans[j]) { System.out.println("NO"); return; } } } else if (mark != '*' && ans[j] != 'b' && ans[j] != '*' && ans[j] == mark) { System.out.println("NO"); return; } } if (mark == '*') mark = 'a'; for (int j = 0; j < n; ++j) { if (ans[j] != 'b') { if (!used[j]) { ans[j] = mark; } else { ans[j] = (mark == 'a' ? 'c' : 'a'); } } } } } System.out.println("YES"); System.out.println(ans); } } class InputReader implements AutoCloseable { private final InputStream in; private int capacity; private byte[] buffer; private int len = 0; private int cur = 0; InputReader(InputStream stream) { this(stream, 100_000); } InputReader(InputStream stream, int capacity) { this.in = stream; this.capacity = capacity; buffer = new byte[capacity]; } private boolean update() { if (cur >= len) { try { cur = 0; len = in.read(buffer, 0, capacity); if (len <= 0) return false; } catch (IOException e) { throw new InputMismatchException(); } } return true; } private int read() { if (update()) return buffer[cur++]; else return -1; } public boolean isEmpty() { return !update(); } private boolean isSpace(int c) { return c == '\n' || c == '\t' || c == '\r' || c == ' '; } private boolean isEscape(int c) { return c == '\n' || c == '\t' || c == '\r' || c == -1; } private int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } int ni() { int c = readSkipSpace(); if (c < 0) throw new InputMismatchException(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c == -1) break; if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; if (res < 0) throw new InputMismatchException(); c = read(); } while (!isSpace(c)); res *= sgn; return res; } int nc() { int c = readSkipSpace(); if (c < 0) throw new InputMismatchException(); return c; } String ns(int initialCapacity) { StringBuilder res = new StringBuilder(initialCapacity); int c = readSkipSpace(); do { res.append((char) (c)); c = read(); } while (!isEscape(c)); return res.toString(); } @Override public void close() throws IOException { in.close(); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
5513b182016a0eda27e7244bdf2a24ff
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.IOException; import java.util.HashSet; import java.util.InputMismatchException; public class GraphAndString { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int M = sc.nextInt(); IntSet[] G = new IntSet[N]; for (int i = 0; i < N; i++) { G[i] = new IntSet(); } for (int i = 0; i < M; i++) { int U = sc.nextInt() - 1; int V = sc.nextInt() - 1; G[U].add(V); G[V].add(U); } char[] S = new char[N]; for (int i = 0; i < N; i++) { if (G[i].size() == N - 1) { S[i] = 'b'; } } for (int i = 0; i < N; i++) { if (S[i] == '\0') { S[i] = 'a'; for (int j = i + 1; j < N; j++) { if (!G[i].contains(j)) { S[j] = 'c'; } } } } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { boolean should = G[i].contains(j); boolean have = (Math.abs(S[i] - S[j]) <= 1); if (should != have) { System.out.println("No"); return; } } } System.out.println("Yes"); System.out.println(new String(S)); } public static class IntSet extends HashSet<Integer> { private static final long serialVersionUID = -525791443646842834L; } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
a6b8b40d6baf1d3346007f3f3e398625
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class GraphString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Set<Integer>[] graph = new Set[n]; Set<Integer> all = new HashSet<>(); for (int i = 0; i < n; i++) { graph[i] = new HashSet<>(); all.add(i); } for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; graph[u].add(v); graph[v].add(u); } Set<Integer> setB = findB(graph); boolean yes = false; if (setB.size() == n) { print(Collections.emptySet(), setB, Collections.emptySet()); yes = true; } else { all.removeAll(setB); Set<Integer> setA = findClique(graph, all); if (setB.size() + setA.size() == n) { print(setA, setB, Collections.emptySet()); yes = true; } else { all.removeAll(setA); Set<Integer> setC = findClique(graph, all); if (setB.size() + setA.size() + setC.size() == n) { yes = true; for (Integer i : setA) { for (Integer c : setC) { if (graph[i].contains(c)) { yes = false; break; } } } } if (yes) { print(setA, setB, setC); } } } if (!yes) { System.out.println("No"); } } private static Set<Integer> findB(Set<Integer>[] graph) { Set<Integer> res = new HashSet<>(); for (int i = 0; i < graph.length; i++) { if (connectedToAll(graph, i)) { res.add(i); } } return res; } private static boolean connectedToAll(Set<Integer>[] graph, Integer cand) { for (int i = 0; i < graph.length; i++) { if (i != cand) { if (!graph[i].contains(cand)) { return false; } } } return true; } private static void print(Set<Integer> a, Set<Integer> b, Set<Integer> c) { System.out.println("Yes"); StringBuilder sb = new StringBuilder(); sb.setLength(a.size() + b.size() + c.size()); for (Integer i : a) { sb.setCharAt(i, 'a'); } for (Integer i : b) { sb.setCharAt(i, 'b'); } for (Integer i : c) { sb.setCharAt(i, 'c'); } System.out.println(sb.toString()); } private static Set<Integer> findClique(Set<Integer>[] graph, Collection<Integer> cands) { Set<Integer> res = new HashSet<>(); for (Integer i : cands) { boolean connectedToAll = true; for (Integer node : res) { if (!graph[i].contains(node)) { connectedToAll = false; break; } } if (connectedToAll) { res.add(i); } } return res; } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
dc9cd9a448540d1c9c718f8724208b45
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.IOException; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < n; ++i) g[i][i] = true; for (int i = 0; i < m; ++i) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; g[a][b] = g[b][a] = true; } solve(n, g); } private static void solve(int n, boolean[][] g) { int f = 0; int s = 1; boolean found = false; for (f = 0; f < n && !found; ++f) { for (s = f + 1; s < n && !found; ++s) { if (!g[f][s]) { found = true; } } } --f; --s; if (!found) { System.out.println("Yes"); for (int i = 0; i < n; ++i) System.out.print("a"); return; } Set<Integer> as = new HashSet<>(); Set<Integer> cs = new HashSet<>(); for (int i = 0; i < n; ++i) { if (!g[f][i]) { cs.add(i); } if (!g[s][i]) { as.add(i); } } for (Integer i : as) { for (Integer j : as) { if (!g[i][j]) { System.out.print("No"); return; } } } for (Integer i : cs) { for (Integer j : cs) { if (!g[i][j]) { System.out.print("No"); return; } } } for (Integer i : as) { for (Integer j : cs) { if (g[i][j]) { System.out.print("No"); return; } } } StringBuilder res = new StringBuilder(); Set<Integer> bs = new HashSet<>(); for (int i = 0; i < n; ++i) { if (as.contains(i)) { res.append('a'); } else if (cs.contains(i)) { res.append('c'); } else { res.append('b'); for (Integer a : as) { if (!g[a][i]) { System.out.print("No"); return; } } for (Integer c : cs) { if (!g[c][i]) { System.out.print("No"); return; } } bs.add(i); } } for (Integer i : bs) { for (Integer j : bs) { if (!g[i][j]) { System.out.print("No"); return; } } } System.out.println("Yes"); System.out.println(res); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
31cc32db2a989266a76631ca37c18a54
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.String; import java.util.Arrays; import java.util.Scanner; import java.util.Comparator; public class C { public static void main(String[] args) { // TODO Auto-generated method stub Scanner reader = new Scanner(System.in); PrintWriter writer= new PrintWriter(System.out); String line = reader.nextLine(); String[] strs = line.split("\\s+"); int n = Integer.parseInt(strs[0]); int m = Integer.parseInt(strs[1]); int[][] edge = new int[n][]; for(int i = 0; i < n; i++){ edge[i] = new int[n]; for(int j = 0; j < n; j++) edge[i][j] = 0; } for(int i = 0; i < m; i++){ line = reader.nextLine(); strs = line.split("\\s+"); edge[Integer.parseInt(strs[0])-1][Integer.parseInt(strs[1])-1] = 1; edge[Integer.parseInt(strs[1])-1][Integer.parseInt(strs[0])-1] = 1; } char[] result = new char[n]; for(int i = 0; i < n; i++) result[i] = 'd'; int[] sum = new int[n]; for(int i = 0; i < n; i++){ sum[i] = 0; for(int j = 0; j < n; j++) sum[i] += edge[i][j]; } for(int i = 0; i < n; i++) if(sum[i] == n-1) result[i] = 'b'; int iter; for(iter = 0; iter < n; iter++) if(result[iter] != 'b'){ result[iter] = 'a'; break; } for(int i = iter+1; i < n; i++){ if(edge[iter][i] == 1 && result[i] == 'd') result[i] = 'a'; if(edge[iter][i] == 0 && result[i] == 'd') result[i] = 'c'; } String print = ""; for(int i = 0; i < n; i++) print += result[i]; //writer.println(print); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if((Math.abs((int)result[i]-(int)result[j]) == 2 && edge[i][j] == 1) || (Math.abs((int)result[i]-(int)result[j]) <= 1 && i != j && edge[i][j] == 0)){ writer.println("No"); reader.close(); writer.flush(); writer.close(); return; } } } writer.println("Yes"); writer.println(print); reader.close(); writer.flush(); writer.close(); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
03d29d5b36f2536335cc443efbb67514
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class Third{ static long mod=1000000007; static boolean v[]=new boolean[10]; //For marking nodes as visited during DFS static int c=0; //No of connected components in graph static ArrayList<Integer>ar[]; public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); //int t=in.readInt(); // while(t-->0) //{ int n=in.readInt(); int m=in.readInt(); int g[][]=new int[n+1][n+1]; int c[]=new int[n+1]; for(int i=1;i<=n;i++) { g[i][i]=1; } for(int i=0;i<m;i++) { int x=in.readInt(); int y=in.readInt(); g[x][y]=1; g[y][x]=1; c[x]++; c[y]++; } char a[]=new char[n+1]; Arrays.fill(a, ' '); int f=0; for(int i=1;i<=n;i++) { if(c[i]==n-1) { a[i]='b'; } } for(int i=1;i<=n;i++) { if(a[i]==' ') { a[i]='a'; for(int j=1;j<=n;j++) { if(a[j]==' ') { if(g[i][j]==1) { a[j]='a'; } else a[j]='c'; } } } } /*LinkedHashSet<Integer>hs=new LinkedHashSet<Integer>(); for(int i=1;i<=n;i++) { int c=0; for(int j=1;j<=n;j++) { if(g[i][j]==1) { c++; } } hs.add(c); } if(hs.size()==1) { for(int x:hs) { if(x==n) { for(int i=1;i<=n;i++) { t+="a"; f=1; } } else { if(n%2==0&&x==n/2) for(int i=1;i<=n/2;i++) { f=1; t+="ac"; } else f=0; } } } else if(hs.size()==2) { int c=0; for(int x:hs) { if(x==n) { c++; t+="b"; } else { int y=x; } } }*/ for (int i = 1; i<=n; i++) { for (int j = 1; j<=n; j++) { if (i == j) continue; if ((abs(a[i] , a[j]) == 2 && g[i][j]==1) || (abs(a[i] , a[j]) < 2 && g[i][j]==0)==true) { System.out.println("No"); return ; } } } pw.println("Yes"); for(int i=1;i<=n;i++) pw.print(a[i]); //} pw.close(); } /* returns nCr mod m */ public static long comb(long n, long r, long m) { long p1 = 1, p2 = 1; for (long i = r + 1; i <= n; i++) { p1 = (p1 * i) % m; } p2 = factMod(n - r, m); p1 = divMod(p1, p2, m); return p1 % m; } /* returns a/b mod m, works only if m is prime and b divides a */ public static long divMod(long a, long b, long m) { long c = powerMod(b, m - 2, m); return ((a % m) * (c % m)) % m; } /* calculates factorial(n) mod m */ public static long factMod(long n, long m) { long result = 1; if (n <= 1) return 1; while (n != 1) { result = ((result * n--) % m); } return result; } /* This method takes a, b and c as inputs and returns (a ^ b) mod c */ public static long powerMod(long a, long b, long c) { long result = 1; long temp = 1; long mask = 1; for (int i = 0; i < 64; i++) { mask = (i == 0) ? 1 : (mask * 2); temp = (i == 0) ? (a % c) : (temp * temp) % c; /* Check if (i + 1)th bit of power b is set */ if ((b & mask) == mask) { result = (result * temp) % c; } } return result; } static boolean isPrime(int number) { if (number <= 1) { return false; } if (number <= 3) { return true; } if (number % 2 == 0 || number % 3 == 0) { return false; } int i = 5; while (i * i <= number) { if (number % i == 0 || number % (i + 2) == 0) { return false; } i += 6; } return true; } public static long gcd(long x,long y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b) { return (int)Math.abs(a-b); } public static long abs(long a,long b) { return (long)Math.abs(a-b); } public static int max(int a,int b) { if(a>b) return a; else return b; } public static int min(int a,int b) { if(a>b) return b; else return a; } public static long max(long a,long b) { if(a>b) return a; else return b; } public static long min(long a,long b) { if(a>b) return b; else return a; } static boolean isPowerOfTwo (long v) { return (v & (v - 1)) == 0; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Pair implements Comparable<Pair> { int a,b; Pair (int a,int b) { this.a=a; this.b=b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.a!=o.a) return Integer.compare(this.a,o.a); else return Integer.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } static long sort(int a[],int n) { int b[]=new int[n]; return mergeSort(a,b,0,n-1);} static long mergeSort(int a[],int b[],long left,long right) { long c=0;if(left<right) { long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right) {long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right) { if(a[i]<=a[j]) {b[k++]=a[i++]; } else { b[k++]=a[j++];c+=mid-i;}} while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } /* USAGE //initialize InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); //read int int i = in.readInt(); //read string String s = in.readString(); //read int array of size N int[] x = IOUtils.readIntArray(in,N); //printline out.printLine("X"); //flush output out.flush(); //remember to close the //outputstream, at the end out.close(); */ static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //StringBuilder sb=new StringBuilder(""); //InputReader in = new InputReader(System.in); // OutputWriter out = new OutputWriter(System.out); //PrintWriter pw=new PrintWriter(System.out); //String line=br.readLine().trim(); //int t=Integer.parseInt(br.readLine()); // while(t-->0) //{ //int n=Integer.parseInt(br.readLine()); //long n=Long.parseLong(br.readLine()); //String l[]=br.readLine().split(" "); //int m=Integer.parseInt(l[0]); //int k=Integer.parseInt(l[1]); //String l[]=br.readLine().split(" "); //l=br.readLine().split(" "); /*int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(l[i]); }*/ //System.out.println(" "); //} }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
a3e54b08631a307a2f9a23ea88e0d90d
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.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 IgorKoval. In the name of nightlife of Novosibirsk where I have never been */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n, m; boolean[][] gr; n = in.readInt(); m = in.readInt(); gr = new boolean[n][n]; for (int iter = 0; iter < m; iter++) { int a = in.readInt() - 1; int b = in.readInt() - 1; gr[a][b] = gr[b][a] = true; } int posA = 0; cyc: for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (i != j && i != k && j != k && gr[i][j] && gr[j][k] && !gr[i][k]) { posA = i; break cyc; } } } } char[] ans = new char[n]; Arrays.fill(ans, 'b'); ans[posA] = 'a'; for (int i = 0; i < n; i++) { if (i == posA) continue; if (!gr[posA][i]) { ans[i] = 'c'; } } for (int a = 0; a < n; a++) { if (ans[a] == 'b') { for (int c = 0; c < n; c++) { if (ans[c] == 'c' && !gr[a][c]) { ans[a] = 'a'; } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (!( gr[i][j] && Math.abs(ans[i] - ans[j]) <= 1 || !gr[i][j] && 2 <= Math.abs(ans[i] - ans[j]) )) { out.printLine("No"); return; } } } out.printLine("Yes"); out.printLine(new String(ans)); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
671e2b81e16faa3031ec975db4820b5f
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class graphAndString { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); int v=scan.nextInt(); apoint[] ps=new apoint[v]; for(int i=0;i<v;i++){ ps[i]=new apoint(); } int e=scan.nextInt(); String ans=""; for(int i=0;i<e;i++){ int x=scan.nextInt(); int y=scan.nextInt(); ps[x-1].cns.add(y-1); ps[y-1].cns.add(x-1); } // for(apoint p:ps){ // System.out.println(p.cns); // } //// fill in b's for(apoint p:ps){ if(p.cns.size()==v-1){ p.c='b'; ans+='b'; } } int f=0; while(ps[f].c=='b'){ f++; if(f==v){ System.out.println("Yes"); System.out.println(p(ps)); return; } } ArrayList<Integer> as=new ArrayList<Integer>(); ps[f].c='a'; ans+='a'; as.add(f); ///fill in a's for(int q:ps[f].cns){ if(ps[q].c==' '){ boolean touchesa=true; for(int a:as){ if(!ps[q].cns.contains(a)){ touchesa=false; break; } } if(touchesa){ ps[q].c='a'; ans+='a'; as.add(q); } } } if(ans.length()==v){ System.out.println("Yes"); System.out.println(p(ps)); return; } ///fill in c's f=0; while(ps[f].c=='b'||ps[f].c=='a'){ f++; if(f==v){ System.out.println("Yes"); System.out.println(p(ps)); return; } } boolean ta=false; for(int w:ps[f].cns){ if(ps[w].c=='a'){ ta=true; break; } } if(!ta){ ps[f].c='c'; ans+='c'; } for(int q:ps[f].cns){ if(ps[q].c==' '){ ta=false; for(int w:ps[q].cns){ if(ps[w].c=='a'){ ta=true; break; } } if(!ta){ ps[q].c='c'; ans+='c'; } } } if(ans.length()==v){ System.out.println("Yes"); System.out.println(p(ps)); }else{ System.out.println("No"); } } static String p(apoint[] ps){ String a=""; for(apoint p:ps){ a+=p.c; } return a; } } class apoint{ ArrayList<Integer> cns; char c; public apoint(){ cns=new ArrayList<Integer>(); c=' '; } } /* 4 5 1 2 2 3 3 4 1 4 2 4 */
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
8c28d062f14f35475129ac16bcb9112b
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class C624 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); List<Integer> bs = new ArrayList<Integer>(); int[][] graph = new int[n+1][n+1]; for (int i =1; i<=n; i++){ graph[i][0] = 0; graph[i][i] = 1; } for (int i = 0; i< m; i++) { line = br.readLine().split(" "); int x = Integer.parseInt(line[0]); int y = Integer.parseInt(line[1]); graph[x][y] = 1; graph[y][x] = 1; if (x == y) { continue; } graph[x][0]++; if (graph[x][0] == n-1) { bs.add(x); } graph[y][0]++; if (graph[y][0] == n-1) { bs.add(y); } } br.close(); for (int y=1; y<=n; y++){ if (graph[y][0] == n-1) { bs.add(y); } } int notb=0; for (int i =1; i<=n && notb == 0; i++){ if (graph[i][0] != n-1) { notb = i; } } Map< Point, List<Integer>> map = new HashMap<>(); for (int i =1; i<=n; i++){ if (graph[i][0] >= n-1){ continue; } Point id = new Point(graph[i][0], graph[i][notb]); if (!map.containsKey(id)){ map.put(id, new ArrayList<Integer>()); } map.get(id).add(i); } if (map.keySet().size() > 2) { System.out.println("No"); return; } // verfica ca sunt componente conexe for (Point key : map.keySet()) { List<Integer> componenta = map.get(key); for (int i = 0; i< componenta.size(); i++) { Integer varf1 = componenta.get(i); for (int j = 0; j<componenta.size() ; j++) { if (graph[varf1][componenta.get(j)] == 0) { // nu e conex System.out.println("No"); return; } } } } char[] str = new char[n]; for (int i : bs) { str[i-1] = 'b'; } Iterator<Point> iterator = map.keySet().iterator(); if (iterator.hasNext()) { for (int i : map.get(iterator.next())) { str[i-1] = 'a'; } } if (iterator.hasNext()) { for (int i : map.get(iterator.next())) { str[i-1] = 'c'; } } System.out.println("Yes"); System.out.println(String.valueOf(str)); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
66251a0af5d2ee9d0081862179e8d099
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static List<Integer> [] adj; static int n,m; static boolean [][] g; static boolean [] vis; static char [] ans; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; Reader.init(System.in); //PrintWriter pw = new PrintWriter("output.out", "UTF-8"); tk = new StringTokenizer(in.readLine()); n = parseInt(tk.nextToken()); m = parseInt(tk.nextToken()); int i,j,a,b; ans = new char[n]; Arrays.fill(ans, '0'); adj = new List[n]; for(i=0; i<n; i++) adj[i] = new ArrayList<Integer>(); g = new boolean[n][n]; for(i=0; i<m; i++) { tk = new StringTokenizer(in.readLine()); a = parseInt(tk.nextToken())-1; b = parseInt(tk.nextToken())-1; g[a][b] = g[b][a] = true; adj[a].add(b); adj[b].add(a); } vis = new boolean[n]; for(i=0; i<n; i++) { if(adj[i].size() == n-1) { ans[i] = 'b'; vis[i] = true; } } for(i=0; i<n; i++) { if(!vis[i]) { dfs(i); break; } } for(i=0; i<n; i++) if(!vis[i]) ans[i] = 'c'; boolean flag = true; out : for(i=0; i<n; i++) { for(j=i+1; j<n; j++) { if(g[i][j]) { if((ans[i]=='a' && ans[j]=='c') || (ans[i]=='c' && ans[j]=='a')) { flag = false; break out; } } else { if((ans[i]=='a' && ans[j]=='a') || (ans[i]=='a' && ans[j]=='b') || (ans[i]=='b' && ans[j]=='a') || (ans[i]=='b' && ans[j]=='b') || (ans[i]=='b' && ans[j]=='c') || (ans[i]=='c' && ans[j]=='b') || (ans[i]=='c' && ans[j]=='c')) { flag = false; break out; } } } } System.out.println(flag ? "Yes\n"+valueOf(ans) : "No"); } static void dfs(int v) { if(vis[v]) return; vis[v] = true; ans[v] = 'a'; for(int w : adj[v]) dfs(w); } } class Tools { public static boolean[] seive(int n) { boolean [] isPrime = new boolean[n+1]; Arrays.fill(isPrime, true); for(int i=2; i*i<=n; i++) if(isPrime[i]) for(int j=i; i*j<=n; j++) isPrime[i*j] = false; isPrime[1] = false; return isPrime; } public static boolean next_permutation(int[] p, int len) { int a = len - 2; while (a >= 0 && p[a] >= p[a + 1]) { a--; } if (a == -1) { return false; } int b = len - 1; while (p[b] <= p[a]) { b--; } p[a] += p[b]; p[b] = p[a] - p[b]; p[a] -= p[b]; for (int i = a + 1, j = len - 1; i < j; i++, j--) { p[i] += p[j]; p[j] = p[i] - p[j]; p[i] -= p[j]; } return true; } public static int lower_bound(Comparable[] arr, Comparable key) { int len = arr.length; int lo = 0; int hi = len-1; int mid = (lo + hi)/2; while (true) { int cmp = arr[mid].compareTo(key); if (cmp == 0 || cmp > 0) { hi = mid-1; if (hi < lo) return mid; } else { lo = mid+1; if (hi < lo) return mid<len-1?mid+1:-1; } mid = (lo + hi)/2; } } public static int upper_bound(Comparable[] arr, Comparable key) { int len = arr.length; int lo = 0; int hi = len-1; int mid = (lo + hi)/2; while (true) { int cmp = arr[mid].compareTo(key); if (cmp == 0 || cmp < 0) { lo = mid+1; if (hi < lo) return mid<len-1?mid+1:-1; } else { hi = mid-1; if (hi < lo) return mid; } mid = (lo + hi)/2; } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) throws UnsupportedEncodingException { reader = new BufferedReader( new InputStreamReader(input, "UTF-8")); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
adb76bc717861705b8d8e6ef520cded4
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.*; import java.util.*; public class Send { private static InputReader in; private static PrintWriter out; private static int B_COUNT = 0; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out, true); int n = in.nextInt(); int m = in.nextInt(); Set<Integer>[] g = new Set[n]; for (int i = 0; i < n; i++) { g[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; g[a].add(b); g[b].add(a); } char[] res = new char[n]; for (int i = 0; i < n; i++) { if (g[i].size() == n - 1) { res[i] = 'b'; B_COUNT++; } } bfs(n, g, res, 'a'); bfs(n, g, res, 'c'); for (char ch : res) { if (ch == 0) { System.out.println("No"); System.exit(0); } } System.out.println("Yes"); System.out.println(new String(res)); out.close(); } private static void bfs(int n, Set<Integer>[] g, char[] res, char v) { Set<Integer> visisted = new HashSet<>(); for (int i = 0; i < n; i++) { if (res[i] == 0) { Queue<Integer> q = new ArrayDeque<>(); q.add(i); visisted.add(i); while (!q.isEmpty()) { int t = q.poll(); res[t] = v; for (int next : g[t]) { if (res[next] == 0 && !visisted.contains(next)) { q.add(next); visisted.add(next); } } } break; } } if (visisted.size() > 1) { for (Integer i : visisted) { if (g[i].size() != B_COUNT + visisted.size() - 1) { System.out.println("No"); System.exit(0); } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
bcf58da637f3768a5d004ce69eee8632
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Queue; public class ProblemC { BufferedReader rd; ProblemC() throws IOException { rd = new BufferedReader(new InputStreamReader(System.in)); compute(); } private void compute() throws IOException { int[] a = intarr(); int n = a[0]; int m = a[1]; boolean[][] e = new boolean[n][n]; for(int i=0;i<m;i++) { a = intarr(); int u = a[0]-1; int v = a[1]-1; e[u][v] = true; e[v][u] = true; } boolean[] vis = new boolean[n]; int[] g = new int[n]; boolean ok = true; free: for(int i=0;i<n;i++) { if(!vis[i]) { boolean found = false; for(int j=0;j<n;j++) { if(i != j && !e[i][j]) { found = true; break; } } if(found) { g[i] = 1; vis[i] = true; Queue<Integer> q = new ArrayDeque<>(); q.add(i); while (!q.isEmpty()) { int c = q.poll(); for (int j = 0; j < n; j++) { if (c != j && !e[c][j]) { if (!vis[j]) { vis[j] = true; q.add(j); g[j] = 4 - g[c]; } else if (g[j] != 4 - g[c]) { ok = false; break free; } } } } } } } if(ok) { vis = new boolean[n]; free: for(int i=0;i<n;i++) { if(!vis[i]) { vis[i] = true; if(g[i] == 0) { g[i] = 2; } Queue<Integer> q = new ArrayDeque<>(); q.add(i); while(!q.isEmpty()) { int c = q.poll(); for(int j=0;j<n;j++) { if(c != j && e[c][j]) { if(g[j] == 0) { g[j] = 2; } if(Math.abs(g[c] - g[j]) == 2) { ok = false; break free; } if(!vis[j]) { vis[j] = true; q.add(j); } } } } } } } out(ok?"Yes":"No"); if(ok) { StringBuilder buf = new StringBuilder(); for(int x: g) { buf.append((char)('a'+x-1)); } out(buf); } } private int[] intarr() throws IOException { return intarr(rd.readLine()); } private int[] intarr(String s) { String[] q = split(s); int n = q.length; int[] a = new int[n]; for(int i=0;i<n;i++) { a[i] = Integer.parseInt(q[i]); } return a; } public String[] split(String s) { if(s == null) { return new String[0]; } int n = s.length(); int start = -1; int end = 0; int sp = 0; boolean lastWhitespace = true; for(int i=0;i<n;i++) { char c = s.charAt(i); if(isWhitespace(c)) { lastWhitespace = true; } else { if(lastWhitespace) { sp++; } if(start == -1) { start = i; } end = i; lastWhitespace = false; } } if(start == -1) { return new String[0]; } String[] res = new String[sp]; int last = start; int x = 0; lastWhitespace = true; for(int i=start;i<=end;i++) { char c = s.charAt(i); boolean w = isWhitespace(c); if(w && !lastWhitespace) { res[x++] = s.substring(last,i); } else if(!w && lastWhitespace) { last = i; } lastWhitespace = w; } res[x] = s.substring(last,end+1); return res; } private boolean isWhitespace(char c) { return c==' ' || c=='\t'; } private static void out(Object x) { System.out.println(x); } public static void main(String[] args) throws IOException { new ProblemC(); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
817c210dfde7cbfb405c9ffcd40937c3
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Arthur Gazizov [2oo7] - Kazan FU */ 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 { private List<Integer>[] g; private char[] s; boolean ok = true; private void dfs(int current, char old) { s[current] = (old == 'a' ? 'c' : 'a'); for (Integer next : g[current]) { if (next == current) continue; if (s[next] == '#') { dfs(next, s[current]); } else { if (s[next] == s[current]) { ok = false; break; } } } } public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); Set<Pair<Integer, Integer>> set = new HashSet<>(); Set<Pair<Integer, Integer>> have = new HashSet<>(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { set.add(Pair.makePair(i, j)); } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; set.remove(Pair.makePair(Math.min(x, y), Math.max(x, y))); have.add(Pair.makePair(Math.min(x, y), Math.max(x, y))); } g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (Pair<Integer, Integer> pair : set) { g[pair.first].add(pair.second); g[pair.second].add(pair.first); } s = new char[n]; Arrays.fill(s, '#'); for (int i = 0; i < n && ok; i++) { if (s[i] == '#') { if (g[i].isEmpty()) { s[i] = 'b'; } else { dfs(i, 'a'); } } } if (ok) for (Pair<Integer, Integer> must : have) { char c1 = s[must.first]; char c2 = s[must.second]; if ((c1 == 'a' && c2 == 'c') || (c1 == 'c' && c2 == 'a')) { ok = false; } } out.printlnYesNo(ok); if (ok) { out.print(new String(s)); } } } static class FastPrinter extends PrintWriter { public FastPrinter(Writer writer) { super(writer); } public FastPrinter(OutputStream out) { super(out); } public void printlnYesNo(boolean condition) { println(condition ? "Yes" : "No"); } public void close() { super.close(); } } static class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public FastScanner(InputStreamReader inputStreamReader) { super(inputStreamReader); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public static boolean isWhiteSpace(int c) { return c >= -1 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (!isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } } static class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static <U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } public Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>) first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>) second).compareTo(o.second); } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
62682fa7122f9a66c84f320e07415c54
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
//package com.codeforces.competitions.year2016.jantomarch.aimtechrounddiv2; import java.io.*; import java.util.*; public final class TaskC { static int n, e; static boolean[][] adj; static char[] set; static int[] degree; static List<Integer>[] list; static InputReader in; static OutputWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new OutputWriter(System.out); solve(); out.flush(); in.close(); out.close(); } static void solve() { n = in.nextInt(); e = in.nextInt(); set = new char[n]; degree = new int[n]; Arrays.fill(set, '.'); createGraph(); for (int i = 0; i < n; i++) { if (degree[i] == n - 1) set[i] = 'b'; else set[i] = 'a'; } /* for (int i = 0; i < n; i++) { if (set[i] == '.') set[i] = 'c'; }*/ for (int i = 0; i < n; i++) { if (set[i] == 'a') { for (int j = 0; j < n; j++) { if (i == j) continue; else { if (adj[i][j]) { if (set[j] == 'b') continue; else set[j] = 'a'; } else set[j] = 'c'; } } } } boolean valid = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (set[i] == 'a') { if (set[j] == 'a' || set[j] == 'b') { if (!adj[i][j]) { valid = false; break; } } else if (set[j] == 'c') { if (adj[i][j]) { valid = false; break; } } } else if (set[i] == 'c') { if (set[j] == 'c' || set[j] == 'b') { if (!adj[i][j]) { valid = false; break; } } else if (set[j] == 'a') { if (adj[i][j]) { valid = false; break; } } } } if (!valid) break; } /* System.out.println("set array : "); for (int i = 0; i < n; i++) { System.out.println("i : " + i + ", set[i] : " + set[i]); }*/ if (valid) { System.out.println("Yes"); for (int i = 0; i < n; i++) System.out.print(set[i]); } else System.out.println("No"); } static void createGraph() { adj = new boolean[n][n]; for (int i = 0; i < e; i++) { int from, to; from = in.nextInt() - 1; to = in.nextInt() - 1; adj[from][to] = adj[to][from] = true; degree[from]++; degree[to]++; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() // problematic { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() // not completely accurate { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static class CMath { static long power(long number, int power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long mod(long number, long mod) { return number - (number / mod) * mod; } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
a9efc99cfed261165444c9503fa8b2fa
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
/** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class aimtech_C { static int[] vis; static int c=1; static ArrayList<Integer> e[]; static ArrayList<Character> ne[]; static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args){ FastScanner s = new FastScanner(System.in); StringBuilder op=new StringBuilder(); int n=s.nextInt(); int m=s.nextInt(); int[][] ed=new int[n+1][n+1]; vis=new int[n+1]; e=new ArrayList[n+1]; for(int i=1;i<=m;i++){ int u=s.nextInt(); int v=s.nextInt(); ed[u][v]=ed[v][u]=1; if(e[v]==null)e[v]=new ArrayList<>(); if(e[u]==null)e[u]=new ArrayList<>(); e[v].add(u);e[u].add(v); } char[] an=new char[n+1]; HashMap<Integer,Character> mp=new HashMap<>(); for(int i=1;i<=n;i++){ int c=0; for(int j=1;j<=n;j++){ if(ed[i][j]==1)c++; } if(c==n-1)mp.put(i,'b'); } // // System.out.println(mp.size()); for(int i=1;i<=n;i++){ if(!mp.containsKey(i)){ // System.out.println(i); mp.put(i,'a'); for(int j=1;j<=n;j++) { if(ed[i][j]==1&&!mp.containsKey(j)) { mp.put(j, 'a'); // System.out.println(i + " " + j); } } break; } } for(int i=1;i<=n;i++){ if(!mp.containsKey(i)){ // System.out.println(i); mp.put(i,'c'); for(int j=1;j<=n;j++) { if(ed[i][j]==1&&!mp.containsKey(j)) mp.put(j, 'c'); } break; } } boolean fl=true; Queue<Integer> q=new LinkedList<>(); //System.out.println("hello"); for(int i=1;i<=n;i++) if(mp.get(i)==null)fl=false; if(!fl){ System.out.println("No");return; } for(int i=1;i<=n;i++){ if(vis[i]==0){ q.add(i); vis[i]=1; while(!q.isEmpty()){ int v=q.poll(); if(e[v]!=null){ for(int ad:e[v]){ if(vis[ad]==0){ q.add(ad);vis[ad]=1; //if(mp.get(ad)==null||mp.get(v)==null)fl=false; if( (mp.get(ad)=='c' &&mp.get(v)=='a')|| (mp.get(v)=='c'&&mp.get(ad)=='a') ) fl=false; } } } } } } if(!fl){ System.out.println("No");return; } ArrayList<Integer>[] al=new ArrayList[3]; al[0]=new ArrayList();al[1]=new ArrayList();al[2]=new ArrayList(); for(int i=1;i<=n;i++) { if(mp.get(i)=='a')al[0].add(i); if(mp.get(i)=='b')al[1].add(i); if(mp.get(i)=='c')al[2].add(i); } for(int i=0;i<3;i++){ for(int j=0;j<al[i].size();j++) { for(int k=j+1;k<al[i].size();k++) if(ed[al[i].get(j)][al[i].get(k)]!=1) fl=false; } } if(!fl) { System.out.println("No");return;} op.append("Yes\n"); for (int i = 1;i<= n;i++) { op.append(mp.get(i)); } System.out.println(op); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
57b1c7c23d5c4e0abc8715855372312a
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; public class codef { public static void main(String[] args) throws IOException { BufferedReader B = new BufferedReader(new InputStreamReader(System.in)); String[] s = B.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; i++) { String[] data = B.readLine().split(" "); g[Integer.parseInt(data[0]) - 1][Integer.parseInt(data[1]) - 1] = true; g[Integer.parseInt(data[1]) - 1][Integer.parseInt(data[0]) - 1] = true; } StringBuilder str = new StringBuilder(n); if (m == (n * (n - 1)) / 2) { for (int i = 0; i < n; i++) { str.append('a'); } System.out.println("Yes"); System.out.print(str.toString()); return; } for (int i = 0; i < n; i++) { str.append('0'); } boolean isConnected = true; int h = 0; while (isConnected) { for (int i = h + 1; i < n; i++) { if (!g[h][i]) { isConnected = false; str.setCharAt(h, 'a'); break; } } if (isConnected) { str.setCharAt(h, 'b'); h++; } } for (int i = h + 1; i < n; i++) { if (!g[h][i]) str.setCharAt(i, 'c'); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (!g[i][j]) { if ((str.charAt(i) != 'c' && str.charAt(j) != 'c') || str.charAt(i) == str.charAt(j)) { System.out.print("No"); return; } if (str.charAt(i) == '0') str.setCharAt(i, 'a'); } else { if (str.charAt(i) != '0' && str.charAt(j) != '0') { int k = Math.abs(str.charAt(i) - str.charAt(j)); if (k > 1) { System.out.print("No"); return; } } } } if (str.charAt(i) == '0') str.setCharAt(i, 'b'); } if (str.charAt(n - 1) == '0') str.setCharAt(n - 1, 'b'); String f = str.toString(); System.out.println("Yes"); System.out.print(f); } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output
PASSED
06eea6b99473b61ba92996c7c918918e
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
//package CodeForces.Round320; import java.util.*; /** * Created by Ilya Sergeev on 16.09.2015. */ public class Bnap { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); TreeMap<Integer,Integer[]> map = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); for(int i = 2; i <= 2*n; i++){ for(int j = 1; j <= i-1; j++){ map.put(sc.nextInt(), new Integer[]{i,j}); } } int[] out = new int[2*n]; for (Map.Entry<Integer, Integer[]> integerEntry : map.entrySet()) { if(out[integerEntry.getValue()[0]-1] != 0 || out[integerEntry.getValue()[1]-1] != 0) continue; out[integerEntry.getValue()[0]-1] = integerEntry.getValue()[1]; out[integerEntry.getValue()[1]-1] = integerEntry.getValue()[0]; } for (Integer integer : out) { System.out.print(integer + " "); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
c7fe325380b9f0dc893c4c95082eab3a
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.*; import java.awt.Point; import java.io.*; import java.math.BigInteger; public class CodeForces { FastScanner in; PrintWriter out; int searchMax(int mas[][], int n) { int max = 0; for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) max = Math.max(max, mas[i][j]); return max; } Point getFriend (int mas[][], int n, int max) { for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (mas[i][j] == max) return new Point (i+1, j+1); return new Point(0,0); } void correction (int mas[][], int n, Point p) { int x = p.x; int y = p.y; Arrays.fill(mas[x-1], 0); Arrays.fill(mas[y-1], 0); for (int i = 0; i < n; i++) { mas[i][x-1] = 0; mas[i][y-1] = 0; } } public void solve() throws IOException { int n = in.nextInt(); int mas[][] = new int [2*n][2*n]; int result[] = new int [2*n]; for (int i = 1; i < 2*n; i++) { for (int j = 0; j < i; j++) { int curVal = in.nextInt(); mas[i][j] = curVal; } } for (int i = 0; i< n; i++) { int max = searchMax(mas, 2*n); Point p = getFriend(mas, 2*n, max); result[p.x-1] = p.y; result[p.y-1] = p.x; correction (mas, 2*n, p); } for (int i = 0; i < 2*n; i++) System.out.print(result[i] + " "); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); //in = new FastScanner(new File("knapsack.in")); //out = new PrintWriter(new File("knapsack.out")); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextLine() { String ret = null; try { ret = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ret; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } BigInteger nextBigInteger() { return new BigInteger(next()); } Point nextIntPoint() { int x = nextInt(); int y = nextInt(); return new Point(x, y); } Point[] nextIntPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index) { array[index] = nextIntPoint(); } return array; } List<Integer>[] readGraph(int vertexNumber, int edgeNumber, boolean undirected) { List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index) { graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0) { int from = nextInt() - 1; int to = nextInt() - 1; graph[from].add(to); if(undirected) graph[to].add(from); } return graph; } } public static void main(String[] arg) { new CodeForces().run(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
f735e3da7df8b99a1c26030e3e55cb54
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * User: dmitry */ public class Main { public static InputStream is = System.in; public static BufferedReader br = new BufferedReader(new InputStreamReader(is)); public static StringTokenizer stok; public static String next() { String nxt; try { if (stok != null && stok.hasMoreElements()) return stok.nextToken(); if ((nxt = br.readLine()) != null) { stok = new StringTokenizer(nxt); if (stok.hasMoreElements()) return stok.nextToken(); } else return null; } catch (Exception e) { e.printStackTrace(); } return null; } public static Integer nextInt() { return Integer.valueOf(next()); } public static class Pair { public int a; public int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "Pair{" + "b=" + b + ", a=" + a + '}'; } } public static void main(String[] args) { int n = nextInt(); int[][] ms = new int[2 * n + 1][2 * n + 1]; boolean[] bb = new boolean[2 * n + 1]; for (int i = 1; i <= 2 * n - 1; i++) { for (int j = 1; j <= i; j++) { ms[i + 1][j] = nextInt(); ms[j][i + 1] = ms[i + 1][j]; } } List<Pair> l = new ArrayList<>(); int N = n; while (N > 0) for (int i = 1; i <= 2 * n; i++) { if (!bb[i]) { Pair p = tp(i, ms, bb); if (p != null) { N--; bb[p.a] = true; bb[p.b] = true; l.add(p); } } } for (int i = 1; i <= 2 * n; i++) { System.out.println(ss(i, l)); } } private static int ss(int i, List<Pair> l) { for (int j = 0; j < l.size(); j++) { Pair p = l.get(j); if (p.a == i) { return p.b; } else if (i == p.b) { return p.a; } } return -1; } private static Pair tp(int i, int[][] ms, boolean bb[]) { int mx = Integer.MIN_VALUE; int ij = -1; for (int j = 1; j < ms.length; j++) { if (mx < ms[i][j] && !bb[j]) { mx = ms[i][j]; ij = j; } } if (ij < 0) return null; else { int mx2 = Integer.MIN_VALUE; int ji = -1; for (int j = 1; j < ms.length; j++) { if (ms[j][ij] > mx2 && !bb[j]) { mx2 = ms[j][ij]; ji = j; } } if (ji == i) return new Pair(i, ij); } return null; } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
c3ee5cdb601e3510edda68160f5f8d5c
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; public class Tablecity { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Queue<StrengthWrapper> queue = new PriorityQueue<StrengthWrapper>(); for (int i = 2; i <= 2*n; i++) { for (int j = 1; j < i; j++) { queue.add(new StrengthWrapper(i, j, scanner.nextInt())); } } boolean[] marked = new boolean[2*n+1]; int[] output = new int[2*n+1]; while(!queue.isEmpty()) { StrengthWrapper poll = queue.poll(); int i = poll.i; int j = poll.j; if(!(marked[i] || marked[j])) { output[i] = j; output[j] = i; marked[i] = marked[j] = true; } } StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i <= 2*n; i++) { stringBuilder.append(output[i]); stringBuilder.append(" "); } String trim = stringBuilder.toString().trim(); System.out.println(trim); } static class StrengthWrapper implements Comparable<StrengthWrapper> { int i; int j; int strength; public StrengthWrapper(int i, int j, int strength) { this.i = i; this.j = j; this.strength = strength; } @Override public int compareTo(StrengthWrapper strengthWrapper) { return Integer.compare(strengthWrapper.strength, strength); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
d0bc4a6672ed75aff8d2284e80daa7b1
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.awt.Point; import java.io.IOException; import java.io.InputStream; public class B579 { public static void main(String[] args) throws IOException { InputReader reader = new InputReader(System.in); int N = 2*reader.readInt(); Point[] data = new Point[1000001]; for (int x=0; x<N; x++) { for (int y=0; y<x; y++) { int value = reader.readInt(); data[value] = new Point(x,y); } } int[] answer = new int[N]; for (int value=1000000; value>0; value--) { Point p = data[value]; if (p != null && answer[p.x] == 0 && answer[p.y] == 0) { answer[p.x] = p.y+1; answer[p.y] = p.x+1; } } StringBuilder output = new StringBuilder(); for (int value : answer) { output.append(value).append(' '); } System.out.println(output); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final int readInt() throws IOException { return (int)readLong(); } public final long readLong() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new IOException(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i=0; i<size; i++) { array[i] = readInt(); } return array; } public final long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i=0; i<size; i++) { array[i] = readLong(); } return array; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
14f8ed662aae4b450cd8aa0dedf342e9
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
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.StringTokenizer; /** * * @author jairneto */ public class p1 { private static InputReader ir; private static PrintWriter out; private static int person[][], an[]; private static boolean used[]; public static void main(String[] args) throws IOException { person = new int[1000001][2]; an = new int[1001]; used = new boolean[1001]; ir = new InputReader(System.in); out = new PrintWriter(System.out); int n = ir.nextInt(); n *= 2; for (int i = 1; i <= n; i++) { for (int j = 1; j < i; j++) { int x = ir.nextInt(); person[x][0] = i; person[x][1] = j; } } used[0] = true; for (int i = 1000000; i > 0; i--) { if (!used[person[i][0]] && !used[person[i][1]]) { used[person[i][0]] = true; used[person[i][1]] = true; an[person[i][0]] = person[i][1]; an[person[i][1]] = person[i][0]; } } for (int i = 1; i <= n; i++) { if (i > 1) { out.print(" "); } out.print(an[i]); out.flush(); } } 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()); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
7f670ac2b2c81ce004ef2efa5ffb2782
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; /* * Author: * Rajkin Hossain */ public class Main{ public static void main(String [] args) throws IOException{ InputStream inputStream; //inputStream = new FileInputStream("E:/in2.txt"); inputStream = System.in; FI k = new FI(inputStream); FO z = new FO(); while(k.hasNext()){ int n = k.nextInt(); int nn = n*2; int i = 2; int j = 1; PriorityQueue<T> q = new PriorityQueue<T>(); while(i<=nn){ for(int c = 1;c<=j;c++){ int value = k.nextInt(); q.add(new T(i,c,value)); } ++i; ++j; } boolean [] mark = new boolean[nn+1]; int [] friend = new int[nn+1]; int pair = 0; while(!q.isEmpty()){ T a = q.poll(); if(mark[a.x] == false && mark[a.y] == false){ friend[a.x] = a.y; friend[a.y] = a.x; mark[a.x] = true; mark[a.y] = true; pair++; if(pair == n) break; } } z.print(friend[1]); for(int c = 2;c<=nn;c++){ z.print(" "+friend[c]); } z.println(); } z.flush(); } static class T implements Comparable{ int x; int y; int w; public T(int xx,int yy,int ww){ x = xx; y = yy; w = ww; } public int compareTo(Object o) { return ((T)o).w - this.w; } } public static class FI { BufferedReader br; StringTokenizer st; public FI(InputStream stream){ br = new BufferedReader(new InputStreamReader(stream)); } public long nextLong() { return Long.parseLong(nextToken()); } public String next() { return nextToken(); } public boolean hasNext(){ try { return br.ready(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } } public static class FO extends PrintWriter { FO() { super(new BufferedOutputStream(System.out)); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
08c8b7ac48ee5a759680af72ecbfcf7b
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; public class Main { class Node implements Comparable { int value; int l,r; public Node(int value,int l,int r) { this.value=value; this.l=l; this.r=r; } @Override public int compareTo(Object arg) { // TODO Auto-generated method stub Node node=(Node)arg; return (-this.value+node.value); } } public Main() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); int N=Integer.parseInt(in.readLine())*2; int n2=((N)*(N-1))/2; Node store[]=new Node[n2]; int ind=0; for(int i=2;i<=N;i++) { String str[]=in.readLine().split(" "); for(int j=1;j<i;j++) { int v=Integer.parseInt(str[j-1]); store[ind]=new Node(v,j-1,i-1); ind++; } } Arrays.sort(store); int ans[]=new int[N]; Arrays.fill(ans, -1); for(int i=0;i<n2;i++) { int m=store[i].l; int n=store[i].r; if(ans[n]==-1&&ans[m]==-1) { ans[n]=m; ans[m]=n; } } for(int i=0;i<N;i++) out.write(ans[i]+1+" "); out.write("\n"); out.flush(); } public static void main (String[] args) throws Exception { new Main(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
4a05cac5a0ccce6851360e220f9529a7
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.*; import java.util.*; public final class finding_team_members { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static int maxn=10001000; public static void main(String args[]) throws Exception { int n=sc.nextInt(),k=0; Pair[] a=new Pair[maxn]; boolean[] v=new boolean[n<<1|1]; for(int i=2;i<=n<<1;i++) { for(int j=1;j<i;j++) { a[k++]=new Pair(sc.nextInt(),i,j); } } Arrays.sort(a,0,k); int[] res=new int[n<<1|1]; int j=0,cnt=0; while(cnt<n<<1) { Pair curr=a[j]; if(!v[a[j].x1] && !v[a[j].x2]) { v[a[j].x1]=true; v[a[j].x2]=true; res[a[j].x1]=a[j].x2; res[a[j].x2]=a[j].x1; cnt+=2; } j++; } for(int i=1;i<=(n<<1);i++) { out.print(res[i]+" "); } out.close(); } } class Pair implements Comparable<Pair> { int val,x1,x2; public Pair(int val,int x1,int x2) { this.val=val; this.x1=x1; this.x2=x2; } public int compareTo(Pair p1) { return -(Integer.compare(this.val,p1.val)); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
a09f6421779dfcb1f2cecbc9989b76e8
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * Created by pallavi.v on 10/9/2015. */ public class B579 { static int n; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(reader.readLine()); TreeMap<Integer, Pair> map = new TreeMap<>(); for (int i = 2; i <= 2*n; i++) { String[] s = reader.readLine().split(" "); for (int j = 1; j < i; j++) { Pair pair = new Pair(i, j); map.put(Integer.parseInt(s[j-1]), pair); } } Map<Integer, Integer> pairs = new HashMap<>(); while (pairs.size() < 2*n) { Pair pair = map.lastEntry().getValue(); if (!pairs.containsKey(pair.getA()) && !pairs.containsKey(pair.getB())) { pairs.put(pair.getB(), pair.getA()); pairs.put(pair.getA(), pair.getB()); } map.remove(map.lastKey()); } for (int i = 1; i <= 2*n; i++) { System.out.print(pairs.get(i) + " "); } } static class Pair { private int a; private int b; public Pair(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public int getB() { return b; } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
f9a70aa6f5b102a807df5ba9998acbb0
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class B { public static void main(String[] args) { try (final Scanner sc = new Scanner(System.in)) { final int n = sc.nextInt(); final int size = 2 * n; int[][] pair = new int[size][size]; for(int i = 1; i < size; i++){ for(int j = 0; j < i; j++){ pair[i][j] = sc.nextInt(); } } int[] answer = new int[size]; Arrays.fill(answer, -1); for(int i = 0; i < n; i++){ int max = Integer.MIN_VALUE; int fst = -1, snd = -1; for(int j = 1; j < size; j++){ if(answer[j] >= 0){ continue; } for(int k = j - 1; k >= 0; k--){ if(answer[k] >= 0){ continue; } //System.out.println(pair[j][k]); if(max < pair[j][k]){ max = pair[j][k]; fst = k; snd = j; } } } answer[fst] = snd; answer[snd] = fst; } for(int i = 0; i < size; i++){ System.out.print((i == 0 ? "" : " ") + (answer[i] + 1)); } System.out.println(); } } public static class Scanner implements Closeable { private BufferedReader br; private StringTokenizer tok; public Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } private void getLine() { try { while (!hasNext()) { tok = new StringTokenizer(br.readLine()); } } catch (IOException e) { /* ignore */ } } private boolean hasNext() { return tok != null && tok.hasMoreTokens(); } public String next() { getLine(); return tok.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void close() { try { br.close(); } catch (IOException e) { /* ignore */ } } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
0ae4e8373a3b6c75965cfab6d290ce6b
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class ProblemB { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); new ProblemB().solve(in, out); out.close(); } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int k = 2 * n; int[][] a = new int[k][k]; for (int i = 1; i < k; i++) { for (int j = 0; j < i; j++) { a[i][j] = in.nextInt(); } } int[] res = new int[k]; for (int m = 0; m < n; m++) { int max = 0; int row = 0; int col = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < i; j++) { if (max < a[i][j]) { max = a[i][j]; row = i; col = j; } } } for (int i = 0; i < k; i++) { a[i][col] = 0; a[i][row] = 0; } for (int j = 0; j < k; j++) { a[row][j] = 0; a[col][j] = 0; } res[row] = col; res[col] = row; } for (int i = 0; i < k; i++) { out.print(res[i] + 1 + " "); } } static class InputReader { public BufferedReader br; public StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } 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 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
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
8fc80322b25b22dc39b5d22ee433bb1f
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.Scanner; public class FindingTeamMembers { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); n*=2; int[][] person=new int[(int) (1e6+1)][2]; for(int i=1;i<=n;i++) { for(int j=1;j<i;j++) { int x=sc.nextInt(); person[x][0]=i; person[x][1]=j; } } boolean[] used=new boolean[801]; int[] ans=new int[n+1]; for(int i=(int) 1e6;i>=1;i--) { if(!used[person[i][0]]&&!used[person[i][1]]) { used[person[i][0]]=true; used[person[i][1]]=true; ans[person[i][0]]=person[i][1]; ans[person[i][1]]=person[i][0]; } } for(int i=1;i<=n;i++) { System.out.print(ans[i]+" "); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
e64fc28389ddb50c57a778b9ea7a34c6
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; /** * Created by root on 25.09.15. */ public class MyClass { static int[][] arr; static int n; public static void main(String arg[]){ read(); searchPar(); } public static void findSearch(Integer[][] arr, int d, int n){ long max = 0; int left = 0; int right = 0; Arrays.sort(arr, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return Integer.compare(o1[0], o2[0]); } }); for(int i = 0; i < n; i++){ // System.out.println(arr[i][0] + " " + arr[i][1]); } for(int i = 0; i < n; i++ ){ long count = 0; left = right = i; while((left >= 0) && (arr[i][0] - arr[left][0] < d )){ count = count + arr[left][1]; left--; } while((right < n) && (arr[right][0] - arr[i][0] < d )){ if (i != right) count = count + arr[right][1]; right++; } System.out.println(arr[i][0] + " : " + count); if(count > max) max = count; } System.out.println(max); } public static void read(){ Scanner sc = new Scanner(System.in); n = sc.nextInt(); arr = new int[((2*n - 1)*(2*n-1) - (2*n - 1))/2 + (2*n -1)][3]; //System.out.println(((2*n - 1)*(2*n-1) - (2*n - 1))/2 + (2*n -1)); int k = 0; for(int i = 0; i < 2*n - 1; i++){ for(int j = 0; j < i + 1; j++ ){ int count = sc.nextInt(); arr[k][0] = count; arr[k][1] = i + 2; arr[k][2] = j + 1; k++; } } } public static void searchPar(){ Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o2[0], o1[0]); } }); for(int i = 0; i < arr.length; i++){ //System.out.println(arr[i][0] + " : " + arr[i][1] + " : " + arr[i][2]); } boolean[] booleans = new boolean[2*n + 1]; boolean[][] booleansPar = new boolean[2*n + 1][2*n + 1]; for(int i = 0; i < arr.length; i++){ if(!booleans[arr[i][1]] && !booleans[arr[i][2]]){ booleansPar[arr[i][1]][arr[i][2]] = true; booleans[arr[i][1]] = true; booleans[arr[i][2]] = true; } } int[] answer = new int[2*n + 1]; for(int i = 1; i < 2*n + 1; i++){ for(int j = 1; j < 2*n + 1; j++ ){ //System.out.print(booleansPar[i][j] + " "); if(booleansPar[j][i]){ answer[j] = i; answer[i] = j; } // System.out.print(j + " "); } //System.out.println(); } for(int i = 1; i < 2*n + 1; i++) System.out.print(answer[i] + " "); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
8e7c2b9c20a8b210db9698e3b1cc39b2
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class B_320 { static class A implements Comparable<A>{ int i,j,val; public A(int i, int j, int val){ this.i = i; this.j = j; this.val = val; } @Override public int compareTo(A o) { return o.val - val; //降序 } } class myComparetor implements Comparator<A>{ @Override public int compare(A o1, A o2){ return o2.val - o1.val; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); PriorityQueue<A> Q = new PriorityQueue<A>(); int a[] = new int[4*n]; for(int i=2; i<=n*2; i++){ for(int j=1; j<i; j++){ int k = scanner.nextInt(); Q.add(new A(i, j, k)); } } Arrays.fill(a, -1); while(!Q.isEmpty()){ int i = Q.peek().i; int j = Q.poll().j; if( a[i]==-1 && a[j]==-1 ){ a[i] = j; a[j] = i; // System.out.println("a[i] " + a[i] + " a[j] " +a[j]); } // System.out.println("i " + i + " j " + j); } for(int i=1; i<=2*n; i++){ System.out.print(a[i] + " "); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
38604e8b763790388418982bfde3d611
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.*; public class Main { static int n; static Pair p; static int[] mk=new int[1000]; static Queue<Pair> q=new PriorityQueue<Pair>(); static class Pair implements Comparable<Pair> { int x,y,z; Pair(int a,int b,int c) { x=a;y=b;z=c; } public int compareTo(Pair p) { return p.x-this.x; } } public static void main(String[] args) { Scanner in=new Scanner(System.in); n=in.nextInt(); for(int i=2;i<=2*n;i++) for(int j=1;j<i;j++) q.add(new Pair(in.nextInt(),i,j)); while(!q.isEmpty()) { p=q.poll(); if(mk[p.y]==0&&mk[p.z]==0) { mk[p.y]=p.z;mk[p.z]=p.y; } } for(int i=1;i<=2*n;i++) System.out.print(mk[i]+((i==2*n)?"":" ")); System.out.println(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
3688343a7a3a53844ee8669aa981f17c
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.*; import java.util.*; /** * Created by Юля on 16.09.2015. */ public class SolverB578 { public static void main(String[] args) throws IOException { new SolverB578().run(); } BufferedReader br; PrintWriter pw; StringTokenizer tokenizer; public String nextToken() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(br.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException, NumberFormatException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException, NumberFormatException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException, NumberFormatException { return Double.parseDouble(nextToken()); } public void run() throws IOException { // br = new BufferedReader(new FileReader("input.txt")); // pw = new PrintWriter("output.txt"); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); solve(); pw.flush(); pw.close(); } class Team implements Comparable<Team>{ public int strong; public int num1; public int num2; public Team(int strong, int num1, int num2) { this.strong = strong; this.num1 = num1; this.num2 = num2; } @Override public int compareTo(Team o) { return o.strong-strong; } } private void solve() throws IOException { int n=nextInt(); int[] res=new int[2*n+1]; Arrays.fill(res, 0); List<Team> list=new ArrayList<Team>(); for(int i=2;i<=2*n;i++){ for(int j=1;j<i;j++){ list.add(new Team(nextInt(),i,j)); } } Collections.sort(list); for(int i=0;i<list.size();i++){ int num1=list.get(i).num1; int num2=list.get(i).num2; if(res[num1]==0 && res[num2]==0){ res[num1]=num2; res[num2]=num1; } } for(int i=1;i<=2*n;i++){ pw.print(res[i]+" "); } } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
9bb39502b04270e9afe7f6acd1d203c5
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.*; public class template { static LinkedList<strong> s = new LinkedList<strong>(); public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int n = in.nextInt(); for ( int i = 2; i <= 2 * n; i++ ) for ( int j = 1; j < i; j++ ) s.add( new strong( i, j, in.nextInt() ) ); Collections.sort( s ); int[] p = new int[2 * n]; while ( !s.isEmpty() ) { int m1 = s.getFirst().m1; int m2 = s.getFirst().m2; if ( p[m1 - 1] == 0 && p[m2 - 1] == 0 ) { p[m1 - 1] = m2; p[m2 - 1] = m1; } s.removeFirst(); } for ( int i = 0; i < 2 * n; i++ ) System.out.print( p[i] + " " ); in.close(); System.exit( 0 ); } } class strong implements Comparable<strong> { int m1, m2, s; public strong( int m1, int m2, int s ) { this.m1 = m1; this.m2 = m2; this.s = s; } public int compareTo( strong s ) { return s.s - this.s; } public String toString() { return m1 + " " + m2 + " " + s; } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
dc0c66c6f8938f64a9c4575d4d9ddd91
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Solver solver = new Solver(); solver.solve(); } } class Solver { Scanner stdin = new Scanner(System.in); final int MAXN = 800 + 5; int[][] a = new int[MAXN][MAXN]; int[] p = new int[MAXN]; int maxPart(int n, int i) { int val = 0; int id = -1; for (int j = 1; j <= n; j++) { if (j == i || p[j] != 0) continue; if (a[i][j] > val) { val = a[i][j]; id = j; } } return id; } void solve() { int n = stdin.nextInt() * 2; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { a[i][j] = stdin.nextInt(); a[j][i] = a[i][j]; } } for (; ; ) { boolean end = true; for (int i = 1; i <= n; i++) { if (p[i] != 0) continue; end = false; int j = maxPart(n, i); if (maxPart(n, j) == i) { p[i] = j; p[j] = i; } } if (end) break; } for (int i = 1; i <= n; i++) { System.out.printf("%d ", p[i]); } System.out.println(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
899456af5207498564c42717f7017653
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class B320 { private class Node { ArrayList<Link> links; public Node(int n) { links = new ArrayList<Link>(2*n); } public void addLink(Link link) { links.add(link); } public void sort() { Collections.sort(links); } } private class Link implements Comparable{ int index; int index2; int str; public Link(int index, int index2, int str) { this.index = index; this.index2 = index2; this.str = str; } @Override public int compareTo(Object o) { return ((Link)o).str - str; } } public void go() throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String[] s = r.readLine().split(" "); int n = Integer.parseInt(s[0]); Node[] nodes = new Node[n*2+2]; ArrayList<Link> links = new ArrayList<Link>(n*2); int q; for(int i = 2; i < 2*n+2-1; i++) { s = r.readLine().split(" "); for(int j = 1; j < s.length+1; j++) { q = Integer.parseInt(s[j-1]); links.add(new Link(i, j, q)); } } Collections.sort(links); int[] partner = new int[2*n+2]; Arrays.fill(partner, Integer.MIN_VALUE); for(Link link : links) { if(partner[link.index] == Integer.MIN_VALUE && partner[link.index2] == Integer.MIN_VALUE) { partner[link.index] = link.index2; partner[link.index2] = link.index; } } for(int i = 1; i < partner.length-1; i++) { System.out.print(partner[i] + " "); } } public static void main(String[] args) throws IOException { B320 a = new B320(); a.go(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
c9f49874e4acdff7b2068d1351b1c110
train_001.jsonl
1442416500
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Main { class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } class Node implements Comparable<Node> { private int x; private int y; private int s; public Node(int aX, int aY, int aS) { x = aX; y = aY; s = aS; } public int compareTo(Node n) { return n.s - s; } } public void foo() throws IOException { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = 2 * scan.nextInt(); Node[] ns = new Node[n * (n - 1) / 2]; int k = 0; for(int i = 2;i <= n;++i) { for(int j = 1;j <= i - 1;++j) { ns[k++] = new Node(i, j, scan.nextInt()); } } Arrays.sort(ns); int[] ans = new int[n + 1]; int cnt = 0; k = 0; while(cnt < n / 2) { while(true) { if(ans[ns[k].x] == 0 && ans[ns[k].y] == 0) { ans[ns[k].x] = ns[k].y; ans[ns[k].y] = ns[k].x; ++cnt; break; } ++k; } } for(int i = 1;i <= n;++i) { out.print(ans[i] + " "); } out.close(); } public static void main(String[] args) throws IOException { new Main().foo(); } }
Java
["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"]
2 seconds
["2 1 4 3", "6 5 4 3 2 1"]
NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Java 7
standard input
[ "implementation", "sortings", "brute force" ]
8051385dab9d7286f54fd332c64e836e
There are 2n lines in the input. The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i &gt; 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)
1,300
Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.
standard output
PASSED
b1454b8b835166f235ecfccc727481b1
train_001.jsonl
1475494500
There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class E { static int deg[]; static int in[]; static int out[]; static boolean adjMat[][];; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0) { int n = sc.nextInt(); int m = sc.nextInt(); N = n; deg = new int[n]; in = new int[n]; out = new int[n]; adjMat = new boolean[n][n]; adjList = new ArrayList[N]; for(int i = 0; i < N; i++) adjList[i] = new ArrayList<Pair>(); for(int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; adjMat[u][v] = adjMat[v][u] = true; adjList[u].add(new Pair(v, true)); adjList[v].add(new Pair(u, true)); deg[u]++; deg[v]++; } int count = 0; for(int i = 0; i < N; i++) if(deg[i] % 2 == 0) count++; visited = new boolean[N]; for(int i = 0; i < N; i++) if(!visited[i]) { visited2 = new boolean[N]; dfs(i); ArrayList<Integer> odd = new ArrayList<Integer>(); for(int j = 0; j < N; j++) if(visited2[j] && deg[j] % 2 == 1) odd.add(j); for(int j = 0; j < odd.size(); j += 2) { int u = odd.get(j); int v = odd.get(j + 1); adjList[u].add(new Pair(v, true)); adjList[v].add(new Pair(u, true)); } getEurlerianTour(i); } System.out.println(count); for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) if(adjMat[i][j]) System.out.println((i + 1) + " " + (j + 1)); } } static boolean visited[]; static boolean visited2[]; static void dfs(int u) { if(visited[u]) return; visited[u] = true; visited2[u] = true; for(int i = 0; i < N; i++) if(adjMat[u][i]) dfs(i); } static int N; static ArrayList<Pair> adjList[]; static void getEurlerianTour(int u) { for(Pair p : adjList[u]) if(p.valid) { p.valid = false; for(Pair p2 : adjList[p.v]) if(p2.valid && p2.v == u) { p2.valid = false; break; } if(adjMat[p.v][u] && adjMat[u][p.v]) adjMat[p.v][u] = false; getEurlerianTour(p.v); } } static class Pair { int v; boolean valid; public Pair(int x, boolean y) { v = x; valid = y; } } }
Java
["2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2"]
2 seconds
["3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7"]
null
Java 11
standard input
[ "greedy", "graphs", "constructive algorithms", "flows", "dfs and similar" ]
4f2c2d67c1a84bf449959b06789bb3a7
The first line contains a positive integer t (1 ≤ t ≤ 200) — the number of testsets in the input. Each of the testsets is given in the following way. The first line contains two integers n and m (1 ≤ n ≤ 200, 0 ≤ m ≤ n·(n - 1) / 2) — the number of cities and the number of roads in Berland. The next m lines contain the description of roads in Berland. Each line contains two integers u and v (1 ≤ u, v ≤ n) — the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities. It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200. Pay attention that for hacks, you can only use tests consisting of one testset, so t should be equal to one.
2,200
For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it. In the next m lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once.
standard output
PASSED
fb308c2732c21fe14fd722548558e790
train_001.jsonl
1562339100
You are given $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\ge 4 + 1$$$ and $$$8&gt; 1 + 6$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Codechef { public static void main (String[] args) throws java.lang.Exception { InputReader in = new InputReader(System.in); int N=in.ni(); ArrayList<Integer> a = new ArrayList<Integer>(); for (int x=0;x<N;x++) a.add(in.ni()); Collections.sort(a); // System.out.println (a[N-1]+" "+a[N-2]+" "+a[N-3]); StringBuilder s = new StringBuilder(); if (a.get(N-1)<a.get(N-2)+a.get(N-3)) { s.append ("YES \n"); s.append(a.get(N-1)+" "+a.get(N-2)+" "); for (int x=0;x<N-2;x++) s.append(a.get(x)+" "); } else s.append("NO"); System.out.println (s.toString()); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3\n2 4 3", "5\n1 2 3 4 4", "3\n13 8 5", "4\n1 10 100 1000"]
1 second
["YES\n4 2 3", "YES\n4 4 2 1 3", "NO", "NO"]
NoteOne of the possible arrangements is shown in the first example: $$$4&lt; 2 + 3$$$;$$$2 &lt; 4 + 3$$$;$$$3&lt; 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\ge 8 + 5$$$. There is no solution in the fourth example.
Java 8
standard input
[ "sortings", "greedy", "math" ]
a5ee97e99ecfe4b72c0642546746842a
The first line contains a single integer $$$n$$$ ($$$3\le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \le 10^9$$$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).
1,100
If there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output $$$n$$$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.
standard output
PASSED
bee7277715c6007f9674af1ed4ea244c
train_001.jsonl
1562339100
You are given $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\ge 4 + 1$$$ and $$$8&gt; 1 + 6$$$.
256 megabytes
import java.util.*; public class Temppp { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] arr = new long[n]; for(int i=0 ; i<n ; i++) { arr[i]=sc.nextLong(); } Arrays.sort(arr); long tempp; if(arr[n-2]+arr[n-3]<=arr[n-1] || arr.length<=2) { System.out.println("NO"); } else { tempp=arr[n-1]; arr[n-1]=arr[n-2]; arr[n-2]=tempp; System.out.println("YES"); for(int i=0 ; i<n ; i++) { System.out.print(arr[i]+" "); } } } }
Java
["3\n2 4 3", "5\n1 2 3 4 4", "3\n13 8 5", "4\n1 10 100 1000"]
1 second
["YES\n4 2 3", "YES\n4 4 2 1 3", "NO", "NO"]
NoteOne of the possible arrangements is shown in the first example: $$$4&lt; 2 + 3$$$;$$$2 &lt; 4 + 3$$$;$$$3&lt; 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\ge 8 + 5$$$. There is no solution in the fourth example.
Java 8
standard input
[ "sortings", "greedy", "math" ]
a5ee97e99ecfe4b72c0642546746842a
The first line contains a single integer $$$n$$$ ($$$3\le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \le 10^9$$$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).
1,100
If there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output $$$n$$$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.
standard output
PASSED
92b4716fe5c9733cbd82d48976075d33
train_001.jsonl
1562339100
You are given $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\ge 4 + 1$$$ and $$$8&gt; 1 + 6$$$.
256 megabytes
import java.util.*; import java.io.*; public class NumberCircle { private static void check(long[] array){ for (int i = 0; i < array.length; i++){ long current = array[i]; if (i == 0){ if (current >= (array[array.length - 1] + array[1])){ System.out.println("NO"); return; } } else if (i == array.length - 1){ if (current >= (array[i - 1] + array[0])){ System.out.println("NO"); return; } } else { if (current >= (array[i - 1] + array[i + 1])){ System.out.println("NO"); return; } } } StringBuilder output = new StringBuilder(); for (long num: array){ output.append(num); output.append(" "); } System.out.println("YES"); System.out.println(output.toString()); } public static void main(String[] args) throws IOException{ long N = nextInt(); //In a sorted array of n values let n big the largest. Surround n by n - 1 and n - 2 and continue the cycle until all //the values have been exhausted List<Long> V = new ArrayList<>(); for (int i = 0; i < N; i++){ V.add(nextLong()); } Collections.sort(V); long[] solution = new long[(int)N]; solution[0] = V.get(V.size() - 1); solution[(int) N - 1] = V.get(V.size() - 2); int I = 1; for (int i = V.size() - 3; i >= 0; i--){ solution[I] = V.get(i); I++; } check(solution); } private static StringTokenizer line = new StringTokenizer(""); private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static int nextInt() throws IOException { return Integer.parseInt(getNext()); } private static long nextLong() throws IOException { return Long.parseLong(getNext()); } private static String getNext() throws IOException { if (line.hasMoreTokens()) { return line.nextToken(); } else { line = new StringTokenizer(in.readLine()); return line.nextToken(); } } }
Java
["3\n2 4 3", "5\n1 2 3 4 4", "3\n13 8 5", "4\n1 10 100 1000"]
1 second
["YES\n4 2 3", "YES\n4 4 2 1 3", "NO", "NO"]
NoteOne of the possible arrangements is shown in the first example: $$$4&lt; 2 + 3$$$;$$$2 &lt; 4 + 3$$$;$$$3&lt; 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\ge 8 + 5$$$. There is no solution in the fourth example.
Java 8
standard input
[ "sortings", "greedy", "math" ]
a5ee97e99ecfe4b72c0642546746842a
The first line contains a single integer $$$n$$$ ($$$3\le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \le 10^9$$$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).
1,100
If there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output $$$n$$$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.
standard output
PASSED
b2bebfa3ef188fe4d7e55e868c22ed1a
train_001.jsonl
1390231800
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
256 megabytes
import java.util.* ; import java.io.* ; public class Problems { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); /* 4 0 0 1 0 */ int n = in.nextInt() ; int leftTotal = 0 ; int rightTotal = 0 ; int left [] = new int [n] ; int right[] = new int [n]; ArrayList<Integer> leftIndecies = new ArrayList<>() ; ArrayList<Integer> rightIndecies = new ArrayList<>() ; for(int i = 0; i < n ; ++i){ int temp = in.nextInt() ; if(temp == 0){ leftIndecies.add(i) ; ++leftTotal ; if(i!=0){ left[i]= left[i-1] + 1 ; right[i] = right[i-1] ; } else left[i] = 1; }else{ rightIndecies.add(i) ; ++rightTotal ; if(i!=0){ right[i]=right[i-1]+1; left[i] = left[i-1] ; } else right[i] =1 ; } } long ans = 0 ; int rightListIndex = 0 ; int leftListIndex = leftIndecies.size() -1 ; if (rightTotal < leftTotal) { while (rightTotal > 0) { int tempIndex = rightIndecies.get(rightListIndex++); ans += (long)left[left.length - 1] - left[tempIndex]; --rightTotal; } } else { while (leftTotal > 0) { int tempIndex = leftIndecies.get(leftListIndex--); ans += (long)right[tempIndex]; --leftTotal; } } out.println(ans); out.close(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["4\n0 0 1 0", "5\n1 0 1 0 1"]
1 second
["1", "3"]
NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.
Java 8
standard input
[ "greedy" ]
1a3b22a5a8e70505e987d3e7f97e7883
The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
1,600
Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
6b56831a9eee769557d48e45f6ab5151
train_001.jsonl
1390231800
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.concurrent.*; public class Main { //--------------------------------------------------------------------------- public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); //----------------------------------------------------------------------- int n = in.nextInt(); int[] a = new int[n + 2]; long res = 0; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } int[] p = new int[n + 2]; for (int i = 1; i <= n; i++) { p[i] = a[i]; if (p[i] == 0) { res += p[i - 1]; } p[i] += p[i - 1]; } out.println(res); //----------------------------------------------------------------------- out.close(); } //--------------------------------------------------------------------------- static void shuffleArray(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } static class Pair<F, S> implements Comparable<Pair<F, S>> { F first; S second; public Pair() { } public Pair(F f, S s) { this.first = f; this.second = s; } @Override public boolean equals(Object o) { Pair<F, S> p = (Pair<F, S>) o; if (first.equals(p.first) && second.equals(p.second)) { return true; } return false; } public int compareTo(Pair<F, S> p) { int ret = ((Comparable<F>) first).compareTo(p.first); if (ret == 0) { ret = ((Comparable<S>) second).compareTo(p.second); } return ret; } } static class BitMask { private int mask; public BitMask() { mask = 0; } public BitMask(BitMask b) { mask = b.getMask(); } public BitMask(int i) { mask = i; } public int getMask() { return mask; } public void setMask(int i) { mask = i; } public int get(int i) { return (mask >> i) & 1; } public void set(int i, int v) { if (v == 0) { mask = mask & ~(1 << i); } else { mask = mask | (1 << i); } } public void set(int v) { for (int i = 0; i < 32; i++) { set(i, v); } } public void flip(int i) { mask = mask ^ (1 << i); } public void flip() { for (int i = 0; i < 31; i++) { flip(i); } } public int count() { int ret = 0; for (int i = 0; i < 32; i++) { if (get(i) == 1) { ret++; } } return ret; } public static int grayCode(int i) { return i ^ (i >> 1); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String s = reader.readLine(); if (s == null) { return false; } tokenizer = new StringTokenizer(s); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public void skipLine() { try { tokenizer = null; reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["4\n0 0 1 0", "5\n1 0 1 0 1"]
1 second
["1", "3"]
NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.
Java 8
standard input
[ "greedy" ]
1a3b22a5a8e70505e987d3e7f97e7883
The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
1,600
Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
096d0579f97fa311f975b19104cdbe2f
train_001.jsonl
1390231800
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
256 megabytes
import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.io.IOException; import java.util.Scanner; public class Other { static int n; static int[] arr; public static void main(String[] args) throws NumberFormatException, IOException { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; long[] cum = new long[n]; for(int i=0; i<n; i++) { arr[i] = in.nextInt(); if(arr[i] == 1) { cum[i] = 1; } if(i - 1 >= 0) { cum[i] += cum[i-1]; } } long ans = 0; for(int i=n-1; i>=1; i--) { if(arr[i] == 0) { ans += cum[i-1]; } } System.out.println(ans); } }
Java
["4\n0 0 1 0", "5\n1 0 1 0 1"]
1 second
["1", "3"]
NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.
Java 8
standard input
[ "greedy" ]
1a3b22a5a8e70505e987d3e7f97e7883
The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
1,600
Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
3cc21fd96a6f5d3b42f3be5c05719953
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { static Scanner input=new Scanner(System.in); public static void main(String args[]) { int test=input.nextInt(); for(int t=0;t<test;t++) { int n=input.nextInt(); int s=input.nextInt(); int k=input.nextInt(); int arr[]=new int[k]; for(int i=0;i<k;i++) { arr[i]=input.nextInt(); } System.out.println(count(n,s,k,arr)); } } public static int count(int n,int s,int k,int arr[]) { Arrays.sort(arr); int indx=-1; for(int i=0;i<k;i++) { if(arr[i]==s) { indx=i; break; } } if(indx==-1) { //System.out.println(0); return 0; } int count_l=0,count_r=0; boolean left=false,right=false; for(int i=indx;i>0;i--) { if(arr[i-1]==arr[i]-1) { count_l++; } else { count_l++; left=true; break; } } if(!left && arr[0]!=1) { left=true; count_l++; } for(int i=indx;i<arr.length-1;i++) { if(arr[i+1]==arr[i]+1) { count_r++; } else { count_r++; right=true; break; } } if(!right && arr[arr.length-1]!=n) { right=true; count_r++; } //System.out.println(count_l+" "+count_r+" "+left+" "+right); if(left && right) { if(count_l<count_r) { return count_l; } else { return count_r; } } else if(left) { return count_l; } else { return count_r; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
97efd25ff89f387a625fc26f6166c671
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Div2A_614 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int[] ans=new int[t]; for (int i=0;i<t;i++) { int n=sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); int[] a=new int[k]; for (int j=0;j<k;j++) a[j]=sc.nextInt(); Arrays.sort(a); if(Arrays.binarySearch(a,s)<0) ans[i]=0; else { int low=s-1; int high=s+1; while (low>0) { if(Arrays.binarySearch(a,low)<0) break; else low--; } while (high<=n) { if(Arrays.binarySearch(a,high)<0) break; else high++; } if(low==0) ans[i]=high-s; else if (high==n+1) ans[i]=s-low; else ans[i]=Math.min((s-low),(high-s)); } } for (int i=0;i<t;i++) System.out.println(ans[i]); } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
8109ad77cf955b0cf2fe1f9a1f808bc8
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import javax.swing.plaf.synth.SynthSeparatorUI; public class temp1 { public static void main(String[] args) throws IOException { Reader scn = new Reader(); // Scanner scn = new Scanner(System.in); int t = scn.nextInt(); z: while (t-- != 0) { long n = scn.nextLong(), s = scn.nextLong(), k = scn.nextLong(); HashSet<Long> hm = new HashSet<>(); for (int i = 0; i < k; i++) hm.add(scn.nextLong()); for (long i = 0; i < 3000; i++) { if (!hm.contains(s - i) && s - i > 0) { System.out.println(i); continue z; } if (!hm.contains(s + i) && s + i <= n) { System.out.println(i); continue z; } } } } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if(a== 0) // return b; // // return gcd(b%a,a); // } // static class comp implements Comparator<pair> { // // @Override // public int compare(pair o1, pair o2) { // // return (int) (o1.y - o1.y); // } // // } private static int f(int x) { int[] a = new int[100]; for (int i = 0; i < 100; i++) a[i] = 100; Arrays.sort(a); ; return 5; } 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[100000 + 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; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
cdc8de32b3c74b3e8de77e4d623a0818
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
//package com.company; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static 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; } } static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } static int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the // middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present // in array return -1; } public static int search(int arr[], int x) { int n = arr.length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } public static void main(String[] args) throws IOException { // write your code here FastReader scanner = new FastReader(System.in); int number = Integer.parseInt(scanner.next()); for(int i = 0; i<number; i++) { int n = scanner.nextInt(); int s = scanner.nextInt(); int k = scanner.nextInt(); int []close = new int[k]; // ArrayList<Integer> close = new ArrayList<>(); for(int j = 0; j < k; j++){ // close.add(scanner.nextInt()); close[j] = scanner.nextInt(); } for(int j = 0; j <= k; j++){ if(s-j >=1 && search(close,s-j) == -1){ out.println(j); break; } if(s+j <= n && search(close,s+j) == -1){ out.println(j); break; } } // sort(close,0, close.length-1); // int found; // int result = 0; // for(int m = 1; m <= n; m++){ // found = binarySearch(close,0, close.length-1,m); // if(result != 0 && Math.abs(m-s) > result){ // break; // } // if(found == -1 ){ // result = Math.abs(m-s); // if(result == 0){break;} // } // } // out.println(result); } out.flush(); out.close(); } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
970afc358fbeaf2846757914c3fc93e0
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public final class Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t>0){ int n=sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); HashSet<Integer> hashs=new HashSet<>(); while(k>0){ hashs.add(sc.nextInt()); k--; } int res=solve(s,n,hashs); System.out.println(res); t--; } } public static int solve(int s,int n,HashSet<Integer> hs){ int x=0; if(!hs.contains(s)) return x; int p1=s,p2=s; while(p1>0 && p2<=n && x<1001){ if(!hs.contains(p1)){ return x; } p1--; if(!hs.contains(p2)){ return x; } p2++; x++; } while(p1>0 && x<1001){ if(!hs.contains(p1)){ return x; } p1--; x++; } while(p2<=n && x<1001){ if(!hs.contains(p2)){ return x; } p2++; x++; } return x; } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
c7b04d6448eef046746776b82f74c2da
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while (t > 0) { int n, s, k; n = sc.nextInt(); s = sc.nextInt(); k = sc.nextInt(); int x; List<Integer> list = new ArrayList<>(); for (int i = 0; i < k; i++) { x = sc.nextInt(); list.add(x); } int cnt = 0; while(true) { if(s+cnt<=n && !list.contains(s+cnt)) break; if(s-cnt>=1 && !list.contains(s-cnt)) break; cnt++; } System.out.println(cnt); t--; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
8faa082daa0eb2d648d82985fbf1943e
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int tt = sc.nextInt(); while(tt-- > 0) { int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0 ; i < k ; i++){ set.add(sc.nextInt()); } int up = Integer.MAX_VALUE; int down = Integer.MAX_VALUE; if(!set.contains(s)){ System.out.println(0); }else{ boolean d = false; int fi = Integer.MIN_VALUE; for(int i = s-1 ; i >=1 ; i--){ if(!set.contains(i)){ d = true; fi = Math.max(i , fi); break; } } boolean u = false; int fj = Integer.MAX_VALUE; for(int i = s+1 ; i <=n ; i++){ if(!set.contains(i)){ u = true; fj = Math.min(i , fj); break; } } if(!d){ System.out.println(fj-s); }else if(!u){ System.out.println(s - fi); }else { System.out.println(Math.min((fj-s) , (s-fi))); } } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
fad40e8e9d7271ff2039eb2103df9808
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; public class CodeForces1 { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { int n = scan.nextInt(); int s = scan.nextInt(); int k = scan.nextInt(); HashSet<Integer> closedFloors = new HashSet<>(); for (int j = 0; j < k; j++) { closedFloors.add(scan.nextInt()); } for (int l = 0; l < k + 1; l++) { if ((!closedFloors.contains(s - l) && (s-l) > 0) || (!closedFloors.contains(s + l) && (s + l) <= n)) { System.out.println(l); break; } } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
1d83c495a7269cabbd734819351a3a1e
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.stream.Collectors; public class SolutionA extends Thread { 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; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new Thread(null, new SolutionA(), "Main", 1 << 26).start(); } public void run() { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } private static void solve() { int n = scanner.nextInt(); int s = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[k]; for (int i = 0; i < k; i++) { a[i] = scanner.nextInt(); } Arrays.sort(a); int nextOpenDown = s; int nextOpenUp = s; for (int i = 0; i < k; i++) { if (a[i] == nextOpenUp) { nextOpenUp++; } } for (int i = k - 1; i >= 0; i--) { if (a[i] == nextOpenDown) { nextOpenDown--; } } if (nextOpenDown == 0) { System.out.println(nextOpenUp - s); } else if (nextOpenUp == n + 1) { System.out.println(s - nextOpenDown); } else { System.out.println(Math.min(nextOpenUp - s, s - nextOpenDown)); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
76e39706ed12c6c6b12177ff44cfd1e6
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int i; int j; for(i=0;i<t;i++){ long n=sc.nextInt(); long s=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[k]; int check=0; int ind=-1; int ans=0; long che; for(j=0;j<k;j++){ a[j]=sc.nextInt(); if(s==a[j]){ check=1; } } if(check==0){ System.out.println(0); } else{ Arrays.sort(a); for(j=0;j<k;j++){ if(s==a[j]){ ind=j; } } // if(ind==(k-1)){ // j=k-2; // che=a[ind]-1; // while(j>=0 && che==a[j]){ // ans++; // che=a[j]-1; // j--; // } // System.out.println(ans+1); // } // else if(ind==0){ // j=1; // che=a[ind]+1; // while(j<k && che==a[j]){ // ans++; // che=a[j]+1; // j++; // } // System.out.println(ans+1); // } // else{ int ans1=0; int ans2=0; j=ind-1; che=a[ind]-1; while(j>=0 && che==a[j]){ ans1++; che=a[j]-1; j--; } if(j==-1){ if(a[j+1]==1){ ans1=-1; } } j=ind+1; che=a[ind]+1; while(j<k && che==a[j]){ ans2++; che=a[j]+1; j++; } if(j==(k)){ if(a[j-1]==n){ ans2=-1; } } //System.out.println(ans1); //System.out.println(ans2); if(ans1==-1){ System.out.println(ans2+1); } else if(ans2==-1){ System.out.println(ans1+1); } else if(ans1>ans2){ System.out.println(ans2+1); } else{ System.out.println(ans1+1); } } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
a4957b620faa91be8dfbc4872e93b683
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.lang.*; public class Hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0;i<t;i++) { int n = sc.nextInt(); int p = sc.nextInt(); int k = sc.nextInt(); Set<Integer> val=new HashSet<>(); for(int j=0;j<k;j++) val.add(sc.nextInt()); boolean value=val.contains(p); //System.out.println(value); if(!value) System.out.println("0"); else { int less=-1; for(int j=p-1;j>0;j--) { value = val.contains(j); if(!value) { less=j; break; } } int more=-1; for(int j=p+1;j<=n;j++) { value = val.contains(j); if(!value) { more=j; break; } } //System.out.println(less+" "+more); if(more!=-1 && less!=-1) System.out.println(Math.min(Math.abs(more-p),Math.abs(less-p))); else if(more!=-1) System.out.println(Math.abs(more-p)); else if(less!=-1) System.out.println(Math.abs(less-p)); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
2dca61cdd1e6d265868e7c67e9273947
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; //import java.io.BufferedReader; //import java.io.IOException; //import java.io.InputStreamReader; //import java.io.*; public class call { public static void main(String args[]) { // FastIO io = new FastIO(); // BufferedReader reader = // new BufferedReader(new InputStreamReader(System.in)); Scanner sc= new Scanner(System.in); int tc = sc.nextInt(); while (tc != 0) { solve(sc); //System.out.println(tc); tc--; } } static void solve(Scanner sc) {// io.nextInt(); // System.out.println(tc); // Scanner sc= new Scanner(System.in); int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); int ans = 1000000000 + 7; int[] arr = new int[k]; HashSet<Integer> val = new HashSet<>(); for (int i = 0; i < k; ++i) { int x = sc.nextInt(); // ans = Math.min(ans, Math.abs(x - s)); arr[i] = x; val.add(x); } for (int i = s; i <= n; ++i) { if (!val.contains(i)) { ans = Math.min(ans, i - s); break; } } for (int i = s; i > 0; --i) { if (!val.contains(i)) { ans = Math.min(ans, s - i); break; } } //Arrays.sort(arr); //int index = 0; //for (int i = 0; i < k; ++i) { // if () //System.out.println(arr[i]); //} // ans = Math.min(ans,); System.out.println(ans); } // static class FastIO extends PrintWriter // { // StringTokenizer st = new StringTokenizer(""); // BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); // // FastIO() // { // super(System.out); // } // // String next() // { // while (!st.hasMoreTokens()) // { // try { // st = new StringTokenizer(r.readLine()); // } catch (Exception e) { } // } // return st.nextToken(); // } // // int nextInt() // { // return Integer.parseInt(next()); // } // // long nextLong() // { // return Long.parseLong(next()); // } // // double nextDouble() // { // return Double.parseDouble(next()); // } // } //HashSet<Integer> ded = new HashSet<>(); //System.out.println(name); //MyScanner sc = new MyScanner(); // out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String int result = 3*n; out.println(result); // print via PrintWriter */ // Stop writing your solution here. ------------------------------------- //out.close(); //} }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
4c2759d5633e3d437d868221f48cbe1b
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class temp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int minl = Integer.MAX_VALUE; int minu = Integer.MAX_VALUE; int n = sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i=0;i<k;i++) { int a=sc.nextInt(); list.add(a); } if(list.contains(s)) { for(int i=s-1;i>0;i--) { if(!list.contains(i)) { minl = s-i; break; } } for(int i=s+1;i<=n;i++) { if(!list.contains(i)) { minu = i-s; break; } } System.out.println(Math.min(minl, minu)); }else { System.out.println("0"); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
598a1a04de9484e33a9dbb37f1753f21
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Reader in = new Reader(); public static void main(String[] args) throws IOException { //Scanner sc = new Scanner(); Main solver = new Main(); solver.solve(); out.flush(); out.close(); } static int INF = (int)1e9; static int maxn = (int)1e5+5; static int mod = 998244353; static int n,m,q,k,t; void solve() throws IOException{ t = in.nextInt(); while (t --> 0) { n = in.nextInt(); int s = in.nextInt(); k = in.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < k; i++) { set.add(in.nextInt()); } int up = 0, down = 0; while (set.contains(s+up)) up++; while (set.contains(s-down)) down++; int ans = Math.min(down, up); if (s-down <= 0) ans = up; if (s+up > n) ans = down; out.println(ans); } } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
e1f5617cb8d44c51eee7d9d2e3c4efba
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; public class S { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static boolean fa(int s , int arr[]) { for(int i = 0 ; i < arr.length ; i++) { if(arr[i] == s) { return false; } } return true; } public static void main(String args[]) throws IOException{ S.init(System.in); int t = S.nextInt(); while(t-- > 0) { int n = S.nextInt(); int f = S.nextInt(); int k = S.nextInt(); int arr[] = new int[k]; for(int i = 0 ; i < k ; i++) { arr[i] = S.nextInt(); } int ans = 0; for(int i = 0 ; i <= k ; i++) { boolean a = false , b = false; if(f + i <= n) { a = fa(f + i , arr); } if(f - i > 0) { b = fa(f - i , arr); } if(a == true || b == true) { ans = i; break; } } System.out.println(ans); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
9fd28758f4edc605ea91d61eb7d9b464
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; public class noob { InputReader in; final long mod=1000000007; StringBuilder sb; public static void main(String[] args) throws java.lang.Exception { new noob().run(); } void run() throws Exception { in=new InputReader(System.in); sb = new StringBuilder(); int t=i(); for(int i=1;i<=t;i++) { solve(); } System.out.print(sb); } void solve() { int i,j; int n=i(), s=i(), k=i(); HashSet<Integer> set=new HashSet<>(); for(i=0;i<k;i++) set.add(i()); i=s; j=s; int ans=0,x=0; while(x==0) { if(set.contains(i)==true && set.contains(j)==true) { i++; j--; if(i>n) i=n; if(j<1) j=1; ans++; } else { x=1; break; } } sb.append(ans+"\n"); } long power(long x, long y, long p) { long res = 1; 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%p; } int gcd(int a, int b) { return (b==0)?a:gcd(b,a%b); } String s(){return in.next();} int i(){return in.nextInt();} long l(){return in.nextLong();} double d(){return in.nextDouble();} class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-->0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
59d8825d64cc21b2f26d6832db8e89cd
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
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.TreeSet; /** * 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int s = in.nextInt(); int k = in.nextInt(); TreeSet<Integer> set = new TreeSet<>(); for (int j = 0; j < k; j++) { set.add(in.nextInt() - 1); } s--; int ans = 0; while (true) { if (s - ans >= 0 && !set.contains(s - ans) || s + ans < n && !set.contains(s + ans)) break; ans++; } out.println(ans); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
eeab2a1f3da473fa74ed09aa33a38145
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] line = br.readLine().split(" "); long n = Long.parseLong(line[0]); long s = Long.parseLong(line[1]); long k = Long.parseLong(line[2]); String[] kline = br.readLine().split(" "); ArrayList<Long> arr = new ArrayList<>(); for (String kl : kline) arr.add(Long.parseLong(kl)); for (int i = 0; i <= k; i++) { if (s - i > 0 && !arr.contains(s - i)) { System.out.println(i); break; } if (s + i <= n && !arr.contains(s + i)) { System.out.println(i); break; } } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
fc883a77f2a88a8e3eb40b4dc2e8e7c0
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.text.NumberFormat; //import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class Main { public static void main(String[] args) throws IOException { InputStreamReader r = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(r); int t =Integer.parseInt(input.readLine()); for (int i = 0; i < t; i++) { String temp=input.readLine(); String[]t1=temp.split(" "); long n=Long.parseLong(t1[0]); long s=Long.parseLong(t1[1]); long k=Long.parseLong(t1[2]); temp=input.readLine(); t1=temp.split(" "); ArrayList <Long> number=new ArrayList<Long>();; for (int j = 0; j < k; j++) { number.add(Long.parseLong(t1[j])); } int res1=0; int res2=0; for (long j = s;true ; j--) { if(number.contains(j)==false||j==0){ break; } res1++; } for (long j = s;number.contains(j) ; j++) { if(number.contains(j)==false||j>n){ break; } res2++; } if(res1==s){ res1=Integer.MAX_VALUE; } if(res2==(n-s+1)){ res2=Integer.MAX_VALUE; } if(res1>res2){ System.out.println(res2); } else{ System.out.println(res1); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
c7c983667a1f106810d3d326ebd54c7a
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; public class A{ static int max = (int)1e9; public static void main(String[] args) throws Exception{ FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = fs.nextInt(); while(tt-->0) { int n = fs.nextInt(), s = fs.nextInt(), k = fs.nextInt(); HashSet<Integer> set = new HashSet<Integer>(); for(int i=0;i<k;i++) { int p = fs.nextInt(); set.add(p); } if(!set.contains(s)) { out.println(0); continue; } int num = s; while(num>0) { if(set.contains(num)) { num--; } else { break; } } int num2 = s; while(num2<=n) { if(set.contains(num2)) { num2++; } else { break; } } if(num==0) { out.println(num2-s); } else if(num2==n+1) { out.println(s-num); } else { out.println(Math.min(s-num, num2-s)); } } 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 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()); } } static int lowerBound(int[] arr, int l, int r, int k) { while(r>l) { int mid = (l+r)/2; if(arr[mid]>=k) { r = mid; } else { l = mid+1; } } if(arr[l]<k) return -1; return l; } static int upperBound(int[] arr, int l, int r, int k) { while(r>l) { int mid = (l+r)/2; if(arr[mid]>k) { r = mid; } else { l = mid+1; } } if(arr[l]<=k) return -1; return l; } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
0e8b9362b1036482f92ff0cdab807cfb
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
//normal import java.util.*; import java.lang.*; import java.io.*; // String Tokenizer public class Main { public static void main(String[] args) { // code Scanner scn = new Scanner(System.in); // System.out.println("Hi"); int t = scn.nextInt(); while (t > 0) { t--; int n = scn.nextInt(); int s = scn.nextInt(); int k = scn.nextInt(); int[] arr = new int[k]; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < k; i++) { arr[i] = scn.nextInt(); map.put(arr[i], 0); } Arrays.sort(arr); int x = binarySearchL(arr, s); if (x != s) { System.out.println(0); continue; } else { int i = s; while (map.containsKey(i) && i >= 1) { i--; } if (i == 0) { x = Integer.MAX_VALUE; } else { x = s - i; } i = s; while (map.containsKey(i) && i <= n) { i++; } int y; if (i == n + 1) { y = Integer.MAX_VALUE; } else { y = i - s; } System.out.println(Math.min(x, y)); } } } static int binarySearchL(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) { return arr[m]; } if (arr[m] < x) l = m + 1; else r = m - 1; } if (r == -1) { return arr[0]; } return arr[r]; } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
63f2788e24a48a8472c24149130c2791
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
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 { public void solve() throws Exception { int t=sc.nextInt(); long mod=(long)1e9+7; while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); int arr[]=sc.readArray(k); Arrays.parallelSort(arr); int position=Arrays.binarySearch(arr, m); if(position>=0) { int righthalf=-1; int lefthalf=0; for(int i=position;i<k;i++) { if(arr[i]-arr[position]!=i-position) { righthalf=arr[position]+i-position; break; } } if(righthalf==-1) righthalf=arr[k-1]+1; if(righthalf>n) righthalf=-1000000000; for(int i=position;i>=0;i--) { if(arr[i]-arr[position]!=i-position) { lefthalf=arr[position]+position-i; break; } } if(lefthalf==0) { lefthalf=arr[0]-1; } if(lefthalf==0) { lefthalf=Integer.MAX_VALUE/2; } //out.println(righthalf+" "+lefthalf); out.println(Math.min(Math.abs(arr[position]-lefthalf), Math.abs(arr[position]-righthalf))); } else out.println(0); } } static long power(long x, long y, long p) { long res = 1; 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; } } } 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()); } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
7f9923b75f88261a7c5996d9feab3c05
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; 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); AConneRAndTheARCMarklandN solver = new AConneRAndTheARCMarklandN(); solver.solve(1, in, out); out.close(); } static class AConneRAndTheARCMarklandN { int IINF = (int) 1e9 + 331; public void solve(int testNumber, InputReader in, OutputWriter out) { int ntc = in.nextInt(); while ((ntc--) > 0) { int n = in.nextInt(); int s = in.nextInt(); int k = in.nextInt(); int closestF = (int) 2e9 + 5; HashSet<Integer> closedFloors = new HashSet<>(); for (int i = 0; i < k; i++) { closedFloors.add(in.nextInt()); } int minDist = +IINF; for (int i = s; i <= n; i++) { if (!closedFloors.contains(i)) { if (Math.abs(i - s) < minDist) { closestF = i; minDist = Math.abs(i - s); } break; } } for (int i = s; i >= 1; i--) { if (!closedFloors.contains(i)) { if (Math.abs(i - s) < minDist) { closestF = i; minDist = Math.abs(i - s); } break; } } out.println(minDist); } } } 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
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
af0f604e92a8fa3a1ed20808d2103605
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); AConneRAndTheARCMarklandN solver = new AConneRAndTheARCMarklandN(); solver.solve(1, in, out); out.close(); } static class AConneRAndTheARCMarklandN { public void solve(int testNumber, FastReader s, PrintWriter out) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int S = s.nextInt(); int k = s.nextInt(); int[] arr = s.nextIntArray(k); Arrays.sort(arr); int pos = Arrays.binarySearch(arr, S); if (pos < 0) { out.println(0); } else { int curr = S; int diff = Integer.MAX_VALUE; // boolean found = false; while (pos >= 0) { if (arr[pos] != curr) { diff = S - curr; // found = true; break; } pos--; curr--; } pos = Arrays.binarySearch(arr, S); curr = S; while (pos < k) { if (arr[pos] != curr) { diff = Math.min(diff, curr - S); // found = true; break; } pos++; curr++; } if (arr[0] != 1) { diff = Math.min(diff, S - (arr[0] - 1)); } if (arr[k - 1] != n) { diff = Math.min(diff, arr[k - 1] + 1 - S); } out.println(diff); } } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
ab12476af9e04a469d68b43076eb7403
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
//package pkg1293a; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { long n=sc.nextLong(); long s=sc.nextLong(); int k=sc.nextInt(); long array[]=new long[k]; for(int j=0;j<k;j++) { array[j]=sc.nextInt(); } long num1=0,num2=0; //int flage=0; long j; for( j=s;j<=n;j++) { int flage=0; for(int l=0;l<k;l++) { if(array[l]==j) { flage=1; break; } } if(flage==0) break; num1++; } if(j==n+1 ) num1=n+1; // System.out.println("num1:"+num1); for( j=s;j>0;j--) { int flage=0; for(int l=0;l<k;l++) { if(array[l]==j) { flage=1; break; } } if(flage==0) break; num2++; } if(j==0) { num2=n+1; } // System.out.println("num2:"+num2 + " j:"+j); if(num1>num2) { System.out.println(num2); } else { System.out.println(num1); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
22b467bddf7e03958b4138bcba13d33d
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int sum=0,num=0; int n=sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); ArrayList<Integer> x=new ArrayList<>(); for(int i=0;i<k;i++) { x.add(sc.nextInt()); } for(int i=s;i<=n;i++) { if(!x.contains(i)) { sum=i-s; break; } if(i==n) sum=1000000000; } for(int i=s;i>=1;i--) { if(!x.contains(i)) { num=s-i; break; } if(i==1) num=1000000000; } System.out.println(Math.min(sum, num)); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
144055ec7f416080c87b153d9f7c4d75
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[k]; Map<Integer,Integer> map=new HashMap<Integer, Integer>(); for (int i = 0; i <k; i++) { arr[i] = sc.nextInt(); map.put(arr[i],1); } if (map.get(s)==null){ System.out.println(0); }else{ int flag1=0; int index1=s-1; int cnt1=1; while (index1>=1){ if (map.get(index1)==null){ flag1=1; break; } index1--; cnt1++; } int flag2=0; int index2=s+1; int cnt2=1; while (index2<=n){ if (map.get(index2)==null){ flag2=1; break; } index2++; cnt2++; } int res; if (flag1==1&&flag2==1){ res=Math.min(cnt1,cnt2); }else if (flag1==1){ res=cnt1; }else{ res=cnt2; } System.out.println(res); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
fd473f9ebc3968afddda2081ceff2eff
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); double t = input.nextDouble(); int floors[]; for (int i = 0; i < t; i++) { double n = input.nextDouble(); double s = input.nextDouble(); int k = input.nextInt(); floors = new int[k]; for (int index = 0; index < k; index++) { floors[index] = input.nextInt(); } double x = 0 ; for ( ; true ; x++ ) { if ( find (floors , s+x ) == false && s+x <= n) { System.out.println((int)x) ; break ; } if ( find (floors , s-x ) == false && s-x >= 1) { System.out.println((int)x) ; break ; } } } } public static boolean find(int array[], double key) { boolean answer = false; for (int i = 0; i < array.length; i++) { if (key == array[i]) { answer = true; break; } } return answer; } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
09b24104c9e4810afbd4c4eac4657ff6
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(),s=ni(),k=ni(); HashSet<Integer> set = new HashSet<Integer>(); for(int i=1;i<=k;i++) set.add(ni()); for(int i=0;i<=10001;i++){ int lst=Math.min(n,s+i),fst=Math.max(1,s-i); if(!set.contains(lst) || !set.contains(fst)){ pn(i); return; } } pn(-1); } 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=ni(); 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
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
f568ee2aabd92d23fec1b2ed42412875
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf131 implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Cf131(),"Main",1<<27).start(); } static class Pair{ int nod; int ucn; int siz; Pair(int nod,int ucn,int siz){ this.nod=nod; this.ucn=ucn; this.siz = siz; } public static Comparator<Pair> wc = new Comparator<Pair>(){ public int compare(Pair e1,Pair e2){ int c1 = e1.ucn - e1.siz; int c2 = e2.ucn - e2.siz; //reverse order if (c1 < c2) return 1; // 1 for swaping. else if (c1 > c2) return -1; else{ if(e1.siz>e2.siz) return 1; else return -1; } } }; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } //// iterative BFS public static void bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){ b[s]=true; Queue<Integer> q = new LinkedList<>(); q.add(s); while(q.size()!=0){ int i=q.poll(); // w.println(" #"+i+"# "); Iterator<Integer> it =a[i].listIterator(); int z=0; while(it.hasNext()){ z=it.next(); if(!b[z]){ // w.println("* "+z+" *"); b[z]=true; dist[z] = dist[i]+1; // x.add(z); // w.println("@ "+x.get(x.size()-1)+" @"); q.add(z); } } } } ////recursive BFS public static int bfsr(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,int[] pre){ b[s]=true; int p = 0; int t = a[s].size(); for(int i=0;i<t;i++){ int x = a[s].get(i); if(!b[x]){ dist[x] = dist[s] + 1; p+= (bfsr(x,a,dist,b,pre)+1); } } pre[s] = p; return p; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t= sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); Integer[] a= new Integer[k]; HashMap<Integer,Boolean> hm = new HashMap<Integer,Boolean>(); for(int i=0;i<k;i++){ a[i] = sc.nextInt(); hm.put(a[i],true); } int up = -1; for(int i=s;i<=n;i++){ if(!hm.getOrDefault(i,false)){ up = i; break; } } int down = -1; for(int i=s;i>0;i--){ if(!hm.getOrDefault(i,false)){ down = i; break; } } int ans= Integer.MAX_VALUE; if(up!=-1 && down !=-1) ans = Math.min(Math.abs(up-s),Math.abs(s-down)); else if(up!=-1) ans = Math.abs(up-s); else ans = Math.abs(s-down); w.println(ans); } w.flush(); w.close(); } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
1951cb93d11a525bc6e5e003d21d6cdb
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; public class CF1293A extends PrintWriter { CF1293A() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1293A o = new CF1293A(); o.main(); o.flush(); } Random rand = new Random(); void sort(int[] aa, int n) { for (int i = 0; i < n; i++) { int j = rand.nextInt(i + 1); int tmp = aa[i]; aa[i] = aa[j]; aa[j] = tmp; } Arrays.sort(aa, 0, n); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[k]; for (int i = 0; i < k; i++) aa[i] = sc.nextInt(); sort(aa, k); int i = 0; while (i < k && aa[i] < s) i++; int ans; if (i == k || aa[i] != s) ans = 0; else { int r = s; for (int j = i; j < k && aa[j] == r; j++) r++; int l = s; for (int j = i; j >= 0 && aa[j] == l; j--) l--; if (l < 1) ans = r - s; else if (r > n) ans = s - l; else ans = Math.min(s - l, r - s); } println(ans); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
800ed74e6d99e7135856eb38e94bbbb9
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ar { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static boolean[] seen; static int[][] a2; static Map<Integer,Integer> map; static Set<Character> charset ; static Set<Integer> set; static int[]arr; public static void main(String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int T=scn.nextInt(); for(int t=0;t<T;t++){ int n=scn.nextInt(); int s=scn.nextInt(); int k=scn.nextInt(); boolean isFloorClosed=false; set=new HashSet<>(); for(int i=0;i<k;i++){ int num=scn.nextInt(); if(num==s){ isFloorClosed=true; } set.add(num); } if(!isFloorClosed) { System.out.print(0+"\n"); continue; } solve(arr,s,n); } } static void solve(int[] arr, int s, int n){ for(int i=0;i<=n;i++){ if(s-i>=1 && !set.contains(s-i)){ System.out.print((i)+"\n"); return; }else if(s+i<=n && !set.contains(s+i)){ System.out.print((i)+"\n"); return; } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
4fb063799a6499266cbd1b1c38dbe134
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; /** * Only By Abhi_Valani */ 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); Unstoppable solver = new Unstoppable(); int t=in.nextInt(); while(t-->0) solver.solve(in, out); out.close(); } static class Unstoppable { public void solve(InputReader in, PrintWriter out) { int n=in.nextInt(); int s=in.nextInt(); int k=in.nextInt(); HashSet<Integer> h=new HashSet<>(); for(int i=0;i<k;++i) h.add(in.nextInt()); int a=Integer.MAX_VALUE,b=Integer.MAX_VALUE; for(int i=s;i<=Math.min(1000+s,n);++i) { if(!h.contains(i)){ a=i-s; break; } } for(int i=s;i>=Math.max(s-1000,1);--i) { if(!h.contains(i)){ b=s-i; break; } } out.println(Math.min(a,b)); } } 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 long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
d2aec220ca539ce709aa1227bfca39a5
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
/*input 5 5 2 3 */ import java.util.*; import java.lang.*; import java.io.*; public class Main { static Scanner in = new Scanner(System.in); static int ans=Integer.MAX_VALUE; public static void solve() { int n=in.nextInt(),curr=in.nextInt(),k=in.nextInt(); HashSet<Integer> hs = new HashSet<>(); for(int i=0;i<k;i++) { hs.add(in.nextInt()); } for(int i=0;i<=k;i++) { if(curr+i<=n && !hs.contains(curr+i)) { System.out.println(i); return; } if(curr-i>=1 && !hs.contains(curr-i)) { System.out.println(i); return; } } } public static void main (String[] args) { int t=in.nextInt(); while(t-->0) { solve(); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
800562bca0ed063846aa7dc9df558ac1
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.Arrays; import java.util.Scanner; /** * * @author DELL */ public class Codechef { static int fun(int f,int u,int ar[],int n) { if(u<ar.length-1) { if(ar[u+1]==f+1&&f<n) { f= fun(f+1,u+1,ar,n); return f; } if(f==n&&ar[u]==f) return -1; else return f+1; } else if(f<n) return f+1; else return -1; } static int fun1(int f,int u,int ar[]) { if(u>0) { if(ar[u-1]==f-1) { f = fun1(f-1,u-1,ar); return f; } else return f-1; } if(f==1) return -1; else return f-1; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int f=sc.nextInt(); int c=sc.nextInt(); int ar[]=new int[c]; for(int j=0;j<c;j++) { ar[j]=sc.nextInt(); } Arrays.sort(ar); int u= Arrays.binarySearch(ar, f); if(u<0) { System.out.println(0); } else { int f1=fun(f,u,ar,n); int f2=fun1(f,u,ar); if(f2>=0&&f1>=0) { if(f1-f<f-f2) System.out.println(f1-f); else System.out.println(f-f2); } else if(f1<0) System.out.println(f-f2); else if(f2<0) System.out.println(f1-f); } } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
af6ef77dd7d8432573521a99deb0ca1e
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),s=sc.nextInt(),k=sc.nextInt(); HashSet<Integer>closed=new HashSet<Integer>(); for(int i=0;i<k;i++) { closed.add(sc.nextInt()); } int cnt=0,ans=(int)1e9+1; for(int i=s;;i++) { if(i>n) { cnt=(int)1e9+1; } if(!closed.contains(i)) { break; } cnt++; } //System.out.println(cnt); ans=cnt; cnt=0; for(int i=s;;i--) { if(i<=0) { cnt=(int )1e9+1; break; } if(!closed.contains(i)) { break; } cnt++; } //System.out.println(cnt); ans=Math.min(ans, cnt); pw.println(ans); } 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
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
a4fd50b72a5030b5c8a3e0d0c8c8966b
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.util.*; public class Main { static boolean binarySearch(Integer[] arr,int l,int r,int value) { int mid=(l+r)/2; if(l>=r && arr[l]!=value) { return false; } if(arr[mid]==value) { return true; } else if(value<arr[mid]) { return binarySearch(arr,l,mid-1,value); } else { return binarySearch(arr,mid+1,r,value); } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int q=0;q<t;q++){ int n=sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); Integer arr[]=new Integer[k]; for(int i=0;i<k;i++) { arr[i]=new Integer(sc.nextInt()); } Arrays.sort(arr); int min=100000; for(int i=s;i<=((int)Math.min(n,k+s));i++) { boolean exists=binarySearch(arr,0,k-1,i); if(!exists) { min=i-s; break; } } for(int i=s-1;i>=(int)Math.max(s-k,1);i--) { boolean exists=binarySearch(arr,0,k-1,i); if(!exists) { if(s-i<min) { min=s-i; break; } } } System.out.println(min); } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
105c0bf402637cf03a294c1c33277ca6
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class test { public static void main(String[] args) { int test = fs.nextInt(); // int test = 1; for (int t = 0; t < test; t++) { int n = fs.nextInt(); int s = fs.nextInt(); int k = fs.nextInt(); ArrayList<Integer> al = new ArrayList<Integer>(); for (int i = 0; i < k; i++) al.add(fs.nextInt()); Integer c=3; Collections.sort(al); for (int i = 0; i <= k; i++) { if (s - i >= 1 && Collections.binarySearch(al, s-i) <0) { System.out.println(i); break; } if (s + i <= n && Collections.binarySearch(al, s+i) <0) { System.out.println(i); break; } } } } /* * array list * * ArrayList<Integer> al=new ArrayList<>(); creating BigIntegers * * BigInteger a=new BigInteger(); BigInteger b=new BigInteger(); * * hash map * * HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int * i=0;i<ar.length;i++) { Integer c=hm.get(ar[i]); if(hm.get(ar[i])==null) { * hm.put(ar[i],1); } else { hm.put(ar[i],++c); } } * * while loop * * int t=sc.nextInt(); while(t>0) { t--; } * * array input * * int n = sc.nextInt(); int ar[] = new int[n]; for (int i = 0; i < ar.length; * i++) { ar[i] = sc.nextInt(); } */ static class Node { Node left, right; int data; public Node(int data) { this.data = data; } public void insert(int val) { if (val <= data) { if (left == null) { left = new Node(val); } else { left.insert(val); } } else { if (right == null) { right = new Node(val); } else { right.insert(val); } } } public boolean contains(int val) { if (data == val) { return true; } else if (val < data) { if (left == null) { return false; } else { return left.contains(val); } } else { if (right == null) { return false; } else { return right.contains(val); } } } public void inorder() { if (left != null) { left.inorder(); } System.out.print(data + " "); if (right != null) { right.inorder(); } } public int maxDepth() { if (left == null) return 0; if (right == null) return 0; else { int ll = left.maxDepth(); int rr = right.maxDepth(); if (ll > rr) return (ll + 1); else return (rr + 1); } } public int countNodes() { if (left == null) return 1; if (right == null) return 1; else { return left.countNodes() + right.countNodes() + 1; } } public void preorder() { System.out.print(data + " "); if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } } public void postorder() { if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } System.out.print(data + " "); } public void levelorder(Node node) { LinkedList<Node> ll = new LinkedList<Node>(); ll.add(node); getorder(ll); } public void getorder(LinkedList<Node> ll) { while (!ll.isEmpty()) { Node node = ll.poll(); System.out.print(node.data + " "); if (node.left != null) ll.add(node.left); if (node.right != null) ll.add(node.right); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static final Scanner sc = new Scanner(System.in); private static final FastReader fs = new FastReader(); private static final OutputWriter op = new OutputWriter(System.out); static int[] getintarray(int n) { int ar[] = new int[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextInt(); } return ar; } static long[] getlongarray(int n) { long ar[] = new long[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextLong(); } return ar; } static int[][] get2darray(int n, int m) { int ar[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ar[i][j] = fs.nextInt(); } } return ar; } static Pair[] getpairarray(int n) { Pair ar[] = new Pair[n]; for (int i = 0; i < n; i++) { ar[i] = new Pair(fs.nextInt(), fs.nextInt()); } return ar; } static void printarray(int ar[]) { for (int i : ar) { op.print(i + " "); } op.flush(); } static int fact(int n) { int fact = 1; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } // static int getans(int[] a, int[] b) { // int a1 = a[0]; // int a2 = b[0]; // int b1 = a[1]; // int b2 = b[1]; // int c1 = a[2]; // int c2 = b[2]; // // if (((a1 == a2) && (b1 == b2) && (c1 == c2))) // return 0; // else if ((a2 - a1) == (b2 - b1) && (b2 - b1) == (c2 - c1)) // return 1; // else if ((a2 / a1 == b2 / b1) && (b2 / b1 == c2 / c1) && (a2 / a1 == c2 / c1) // && (a2 % a1 == 0 && b2 % b1 == 0 && c2 % c1 == 0)) // return 1; // else if (((a1 == a2) && (b1 == b2)) || ((a1 == a2) && (c1 == c2)) || ((c1 == c2) && (b1 == b2))) { // return 1; // } else if (a1 == a2) { // if ((b2 - b1) == (c2 - c1) || ((b2 / b1 == c2 / c1) && (b2 % b1 == 0 && c2 % c1 == 0))) // return 1; // } else if (b1 == b2) { // if ((a2 - a1) == (c2 - c1) || ((a2 / a1 == c2 / c1) && (a2 % a1 == 0 && c2 % c1 == 0))) // return 1; // } else if (c1 == c2) { // if ((b2 - b1) == (a2 - a1) || ((b2 / b1 == a2 / a1) && (b2 % b1 == 0 && a2 % a1 == 0))) // return 1; // } else if ((((a2 - a1) != (b2 - b1) && (b2 - b1) != (c2 - c1) && (a2 - a1) != (c2 - c1)) // && ((a2 / a1 != b2 / b1) && (b2 / b1 != c2 / c1) && (a2 / a1 != c2 / c1)))) { // return 3; // } else if ((((a2 - a1) != (b2 - b1) && (b2 - b1) != (c2 - c1) && (a2 - a1) != (c2 - c1)))) { // if ((a2 / a1 == b2 / b1 && a2 % a1 != 0 && b2 % b1 != 0) // || (a2 / a1 == c2 / c1 && a2 % a1 != 0 && c2 % c1 != 0) // || (c2 / c1 == b2 / b1 && c2 % c1 != 0 && b2 % b1 != 0)) // return 3; // // } // return 2; // // } // function to find largest prime factor }/* * 1 5 -2 -3 -1 -4 -6till here */ // while (t > 0) { // int a[] = getintarray(3); // int b[] = getintarray(3); // int ans = getans(a, b); // System.out.println(ans); // }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
ef872d759eeda30b32d6c088a0d0509d
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import javax.swing.plaf.synth.SynthSeparatorUI; public class temp1 { public static void main(String[] args) throws IOException { Reader scn = new Reader(); // Scanner scn = new Scanner(System.in); int t = scn.nextInt(); z: while (t-- != 0) { long n = scn.nextLong(), s = scn.nextLong(), k = scn.nextLong(); HashSet<Long> hm = new HashSet<>(); for (int i = 0; i < k; i++) hm.add(scn.nextLong()); for (long i = 0; i < 3000; i++) { if (!hm.contains(s - i) && s - i > 0) { System.out.println(i); continue z; } if (!hm.contains(s + i) && s + i <= n) { System.out.println(i); continue z; } } } } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if(a== 0) // return b; // // return gcd(b%a,a); // } // static class comp implements Comparator<pair> { // // @Override // public int compare(pair o1, pair o2) { // // return (int) (o1.y - o1.y); // } // // } private static int f(int x) { int[] a = new int[100]; for (int i = 0; i < 100; i++) a[i] = 100; Arrays.sort(a); ; return 5; } 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[100000 + 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; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
dc96496d18067a75bc1da474108d084a
train_001.jsonl
1579440900
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
256 megabytes
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 { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t!=0){ int n=sc.nextInt(); int s=sc.nextInt(); int k=sc.nextInt(); HashSet<Integer> set=new HashSet<>(); for(int i=0;i<k;i++){ int a=sc.nextInt(); set.add(a); } int res1=Integer.MAX_VALUE; for(int i=s;i<=n;i++){ if(set.contains(i)){ continue; } res1=i-s; break; } for(int i=s-1;i>0;i--){ if(set.contains(i)){ continue; } res1=Math.min(res1,s-i); break; } System.out.println(res1); t--; } } }
Java
["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"]
1 second
["2\n0\n4\n0\n2"]
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.
Java 11
standard input
[ "binary search", "implementation", "brute force" ]
faae9c0868b92b2355947c9adcaefb43
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.
1,100
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.
standard output
PASSED
351ca31c8e2a6d690522d58c494aaeff
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; public class BloodCousinsReturn { static String[] names; static int[][] adj; static int sz[], lvl[], vis[] , vid = 1; static int[] par; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); par = new int[n]; vis = new int[n]; lvl = new int[n]; sz = new int[n]; q = new int[n]; names = new String[n]; int[] from = new int[n]; int[] to = new int[n]; for (int i = 0; i < n; i++) { names[i] = sc.next(); from[i] = sc.nextInt()-1; par[i] = from[i]; to[i] = i; } adj = packD(n, from, to); for (int i = 0; i < n; i++) if(sz[i] == 0) size(i, -1); for (int i = 0; i < n; i++) if(par[i] == -1) bfs(i); int m = sc.nextInt(); set = new TreeMap[n+1]; qu = new ArrayList[n]; ans = new int[m]; for (int i = 0; i < m; i++) { int v = sc.nextInt()-1; int k = sc.nextInt() + lvl[v]; if(k > n) { ans[i] = 0; continue; } if(qu[v] == null) qu[v] = new ArrayList<Query>(); qu[v].add(new Query(i, k)); } for (int i = 0; i < n; i++) if(lvl[i] == 0) solve(i,-1, false); for (int i = 0; i < m; i++) pw.println(ans[i]); pw.flush(); pw.close(); } static int ans[]; static TreeMap<String, Integer>[] set; private static void solve(int u, int p, boolean keep) { int big = -1; int mx = -1; for (int v : adj[u]) if(v != p && sz[v] > mx) { mx = sz[v]; big = v; } for (int v : adj[u]) if(v != p && v != big) solve(v, u, false); if(big != -1) solve(big, u, true); add(u, p, big); if(qu[u] != null) for (Query query : qu[u]) ans[query.idx] = set[query.kth] != null?set[query.kth].size():0; if(!keep) remove(u,p); } private static void remove(int u, int p) { removeMap(lvl[u], names[u]); for (int v : adj[u]) if(v != p) remove(v, u); } private static void add(int u, int p, int big) { addMap(lvl[u], names[u]); for (int v : adj[u]) if(v != p && v != big) add(v, u, big); } static void addMap(int idx, String s) { if(set[idx] == null) set[idx] = new TreeMap<String, Integer>(); set[idx].put(s, set[idx].getOrDefault(s, 0)+1); } static void removeMap(int idx, String s) { Integer nw = set[idx].remove(s); if(nw == null) return; if(nw-1 > 0) set[idx].put(s, nw-1); } static ArrayList<Query> qu[]; static int q[], s, e; private static void bfs(int root) { q[e++] = root; vis[root] = vid; lvl[root] = 0; while(s < e) { int u = q[s++]; for (int v : adj[u]) { if(vis[v] != vid) { lvl[v] = lvl[u]+1; vis[v] = vid; q[e++] = v; } } } } private static void size(int u, int p) { sz[u]++; for (int v : adj[u]) if(v != p) { size(v, u); sz[u] += sz[v]; } } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static class Query { int idx, kth; public Query(int idx, int kth) { this.idx = idx; this.kth = kth; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
9cbcf4cd314c836b87051d19d6c64d07
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class BloodCousinsReturn { static String[] names; static int[][] adj; static int sz[], lvl[], vis[] , vid = 1; static int[] par; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); par = new int[n]; vis = new int[n]; lvl = new int[n]; sz = new int[n]; q = new int[n]; names = new String[n]; int[] from = new int[n]; int[] to = new int[n]; for (int i = 0; i < n; i++) { names[i] = sc.next(); from[i] = sc.nextInt()-1; par[i] = from[i]; to[i] = i; } adj = packD(n, from, to); for (int i = 0; i < n; i++) if(sz[i] == 0) size(i, -1); for (int i = 0; i < n; i++) if(par[i] == -1) bfs(i); int m = sc.nextInt(); set = new HashMap[n+1]; qu = new ArrayList[n]; ans = new int[m]; for (int i = 0; i < m; i++) { int v = sc.nextInt()-1; int k = sc.nextInt() + lvl[v]; if(k > n) { ans[i] = 0; continue; } if(qu[v] == null) qu[v] = new ArrayList<Query>(); qu[v].add(new Query(i, k)); } for (int i = 0; i < n; i++) if(lvl[i] == 0) solve(i,-1, false); for (int i = 0; i < m; i++) pw.println(ans[i]); pw.flush(); pw.close(); } static int ans[]; static HashMap<String, Integer>[] set; private static void solve(int u, int p, boolean keep) { int big = -1; int mx = -1; for (int v : adj[u]) if(v != p && sz[v] > mx) { mx = sz[v]; big = v; } for (int v : adj[u]) if(v != p && v != big) solve(v, u, false); if(big != -1) solve(big, u, true); add(u, p, big); if(qu[u] != null) for (Query query : qu[u]) ans[query.idx] = set[query.kth] != null?set[query.kth].size():0; if(!keep) remove(u,p); } private static void remove(int u, int p) { removeMap(lvl[u], names[u]); for (int v : adj[u]) if(v != p) remove(v, u); } private static void add(int u, int p, int big) { addMap(lvl[u], names[u]); for (int v : adj[u]) if(v != p && v != big) add(v, u, big); } static void addMap(int idx, String s) { if(set[idx] == null) set[idx] = new HashMap<String, Integer>(); set[idx].put(s, set[idx].getOrDefault(s, 0)+1); } static void removeMap(int idx, String s) { Integer nw = set[idx].remove(s); if(nw == null) return; if(nw-1 > 0) set[idx].put(s, nw-1); } static ArrayList<Query> qu[]; static int q[], s, e; private static void bfs(int root) { q[e++] = root; vis[root] = vid; lvl[root] = 0; while(s < e) { int u = q[s++]; for (int v : adj[u]) { if(vis[v] != vid) { lvl[v] = lvl[u]+1; vis[v] = vid; q[e++] = v; } } } } private static void size(int u, int p) { sz[u]++; for (int v : adj[u]) if(v != p) { size(v, u); sz[u] += sz[v]; } } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static class Query { int idx, kth; public Query(int idx, int kth) { this.idx = idx; this.kth = kth; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
d4a8fc958fa5f95bd857e36340fd36f7
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; public class D { static MultiSet[] set; static String[] name; static int[][] next; static int[] size, ans; static ArrayList<Query>[] queries; static int findSize(int u) { int sz = 1; for(int v: next[u]) sz += findSize(v); return size[u] = sz; } static void add(int u, int h, int x) { set[h].add(name[u]); for(int v: next[u]) if(v != x) add(v, h + 1, x); } static void erase(int u, int h) { set[h].erase(name[u]); for(int v: next[u]) erase(v, h + 1); } static void dfs(int u, int h, boolean keep) { int heavy = -1, max = -1; for(int v: next[u]) if(size[v] > max) max = size[heavy = v]; for(int v: next[u]) if(v != heavy) dfs(v, h + 1, false); if(heavy != -1) dfs(heavy, h + 1, true); add(u, h, heavy); for(Query q: queries[u]) ans[q.idx] = q.k + h >= set.length ? 0 : set[q.k + h].size(); if(!keep) erase(u, h); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); name = new String[N]; int[] cnt = new int[N], p = new int[N]; for(int i = 0; i < N; ++i) { name[i] = sc.next(); p[i] = sc.nextInt() - 1; if(p[i] != -1) cnt[p[i]]++; } build(cnt, p, N); int Q = sc.nextInt(); ans = new int[Q]; queries = new ArrayList[N]; set = new MultiSet[N]; for(int i = 0; i < N; ++i) { queries[i] = new ArrayList<Query>(); set[i] = new MultiSet(); } for(int i = 0; i < Q; ++i) queries[sc.nextInt() - 1].add(new Query(i, sc.nextInt())); size = new int[N]; for(int i = 0; i < N; ++i) if(p[i] == -1) { findSize(i); dfs(i, 0, false); } StringBuilder sb = new StringBuilder(); for(int x: ans) sb.append(x).append('\n'); out.print(sb); out.flush(); out.close(); } static void build(int[] cnt, int[] p, int N) { next = new int[N][]; for(int i = 0; i < N; ++i) { next[i] = new int[cnt[i]]; cnt[i] = 0; } for(int i = 0; i < N; ++i) { int pp = p[i]; if(pp != -1) next[pp][cnt[pp]++] = i; } } static class Query { int idx, k; Query(int a, int b) { idx = a; k = b; } } static class MultiSet { TreeMap<String, Integer> map = new TreeMap<String, Integer>(); void add(String s) { Integer f = map.get(s); if(f == null) f = 0; map.put(s, f + 1); } void erase(String s) { Integer f = map.get(s); if(f == 1) map.remove(s); else map.put(s, f - 1); } int size() { return map.size(); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
797eb05a145266e7a3db53cb7c0b89b8
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class D { static MultiSet[] set; static String[] name; static int[][] next; static int[] size, ans; static ArrayList<Query>[] queries; static int findSize(int u) { int sz = 1; for(int v: next[u]) sz += findSize(v); return size[u] = sz; } static void add(int u, int h, int x) { set[h].add(name[u]); for(int v: next[u]) if(v != x) add(v, h + 1, x); } static void erase(int u, int h) { set[h].erase(name[u]); for(int v: next[u]) erase(v, h + 1); } static void dfs(int u, int h, boolean keep) { int heavy = -1, max = -1; for(int v: next[u]) if(size[v] > max) max = size[heavy = v]; for(int v: next[u]) if(v != heavy) dfs(v, h + 1, false); if(heavy != -1) dfs(heavy, h + 1, true); add(u, h, heavy); for(Query q: queries[u]) ans[q.idx] = q.k + h >= set.length ? 0 : set[q.k + h].size(); if(!keep) erase(u, h); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); name = new String[N]; int[] cnt = new int[N], p = new int[N]; for(int i = 0; i < N; ++i) { name[i] = sc.next(); p[i] = sc.nextInt() - 1; if(p[i] != -1) cnt[p[i]]++; } build(cnt, p, N); int Q = sc.nextInt(); ans = new int[Q]; queries = new ArrayList[N]; set = new MultiSet[N]; for(int i = 0; i < N; ++i) { queries[i] = new ArrayList<Query>(); set[i] = new MultiSet(); } for(int i = 0; i < Q; ++i) queries[sc.nextInt() - 1].add(new Query(i, sc.nextInt())); size = new int[N]; for(int i = 0; i < N; ++i) if(p[i] == -1) { findSize(i); dfs(i, 0, false); } StringBuilder sb = new StringBuilder(); for(int x: ans) sb.append(x).append('\n'); out.print(sb); out.flush(); out.close(); } static void build(int[] cnt, int[] p, int N) { next = new int[N][]; for(int i = 0; i < N; ++i) { next[i] = new int[cnt[i]]; cnt[i] = 0; } for(int i = 0; i < N; ++i) { int pp = p[i]; if(pp != -1) next[pp][cnt[pp]++] = i; } } static class Query { int idx, k; Query(int a, int b) { idx = a; k = b; } } static class MultiSet { HashMap<String, Integer> map = new HashMap<String, Integer>(); void add(String s) { Integer f = map.get(s); if(f == null) f = 0; map.put(s, f + 1); } void erase(String s) { Integer f = map.get(s); if(f == 1) map.remove(s); else map.put(s, f - 1); } int size() { return map.size(); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
851b9d7bec7703224d8a091697b9338a
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; int n; ArrayList<Integer> a[], level[]; int depth[], st[], et[], rev[]; int len = -1; String b[]; void dfs(int u, int p) { st[u] = ++len; rev[len] = u; level[depth[u]].add(st[u]); for (int i : a[u]) { if (i == p) continue; depth[i] = depth[u] + 1; dfs(i, u); } et[u] = len; } int up(int l, int v) { if (l >= level.length) return Integer.MAX_VALUE; int x = 0, r = level[l].size() - 1; int ind = Integer.MAX_VALUE; while (x <= r) { int mid = x + r >> 1; if (level[l].get(mid) < v) x = mid + 1; else { ind = mid; r = mid - 1; } } return ind; } int down(int l, int v) { if (l >= level.length) return -1; int x = 0, r = level[l].size() - 1; int ind = -1; while (x <= r) { int mid = x + r >> 1; if (level[l].get(mid) > v) r = mid - 1; else { ind = mid; x = mid + 1; } } return ind; } class q implements Comparable<q> { int ind, l, r, ans, v; q(int d, int a, int b, int c) { v = d; l = a; r = b; ind = c; } public int compareTo(q o) { return Integer.compare(r, o.r); } } ArrayList<q> o[]; int arr[], m; void update(int x) { x++; while (x <= m) { arr[x]++; x += (x & -x); } } int ans(int x) { int an = 0; x++; while (x > 0) { an += arr[x]; x -= (x & -x); } return an; } void lev(int l) { long val[] = new long[level[l].size()]; HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = val.length - 1; i >= 0; i--) { if (map.containsKey(b[rev[level[l].get(i)]])) val[i] = (((long) map.get(b[rev[level[l].get(i)]])) << 32) | ((long) i); else val[i] = (((long) val.length) << 32) | ((long) i); map.put(b[rev[level[l].get(i)]], i); } Collections.sort(o[l]); Arrays.sort(val); arr = new int[val.length + 1]; m = arr.length - 1; int cnt = val.length - 1; for (int i = o[l].size() - 1; i >= 0; i--) { // out.println(l + " lll " + o[l].get(i).ind); if (o[l].get(i).l > o[l].get(i).r) continue; while (cnt >= 0 && (val[cnt] >> 32) > o[l].get(i).r) update((int) val[cnt--]); o[l].get(i).ans = ans(o[l].get(i).r) - ans(o[l].get(i).l - 1); } // out.println(level[l].size() + " level " + cnt + " " + o[l].size()); } @SuppressWarnings("unchecked") void solve() { n = ni(); a = new ArrayList[n + 1]; level = new ArrayList[n + 1]; depth = new int[n + 1]; st = new int[n + 1]; et = new int[n + 1]; rev = new int[n + 1]; b = new String[n + 1]; for (int i = 0; i <= n; i++) { a[i] = new ArrayList<Integer>(); level[i] = new ArrayList<Integer>(); } b[0] = "0"; for (int i = 1; i <= n; i++) { b[i] = ns(); int r = ni(); a[r].add(i); a[i].add(r); } dfs(0, 0); int m = ni(); q c[] = new q[m]; o = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) o[i] = new ArrayList<q>(); for (int i = 0; i < m; i++) { int v = ni(), k = ni(); c[i] = new q(v, up(depth[v] + k, st[v]), down(depth[v] + k, et[v]), i); // out.println(depth[v] + k + " " + c[i].l + " " + c[i].r); if (depth[v] + k <= n) o[depth[v] + k].add(c[i]); } for (int i = 1; i <= n; i++) lev(i); for (int i = 0; i < m; i++) out.println(c[i].ans); } void soln() { is = System.in; out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) { new CODEFORCES().soln(); } // To Get Input // Some Buffer Methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
defc9cd377e2519280dcfaba7122b1b6
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static ArrayList<Integer> adjList[], queries[]; static String[] name; static int[] size, level, tin, tout, vertex, biggest, queryLevels, ans; static HashMap<String, Integer> map[]; static int time, n; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); adjList = new ArrayList[n]; queries = new ArrayList[n]; map = new HashMap[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<>(); queries[i] = new ArrayList<>(); map[i] = new HashMap<>(); } ArrayList<Integer> roots = new ArrayList<>(); name = new String[n]; for (int i = 0; i < n; i++) { name[i] = sc.next(); int parent = sc.nextInt() - 1; if (parent == -1) roots.add(i); else adjList[parent].add(i); } level = new int[n]; size = new int[n]; tin = new int[n]; tout = new int[n]; vertex = new int[n]; biggest = new int[n]; for (int root : roots) dfs(root, 0); int q = sc.nextInt(); queryLevels = new int[q]; for (int i = 0; i < q; i++) { queries[sc.nextInt() - 1].add(i); queryLevels[i] = sc.nextInt(); } ans = new int[q]; for (int root : roots) solve(root, 0); for (int x : ans) out.println(x); out.flush(); out.close(); } static void solve(int u, int keep) { for (int v : adjList[u]) if (v != biggest[u]) solve(v, 0); if (biggest[u] != -1) solve(biggest[u], 1); for (int v : adjList[u]) { if (v == biggest[u]) continue; for (int i = tin[v]; i <= tout[v]; i++) { int node = vertex[i]; map[level[node]].put(name[node], map[level[node]].getOrDefault(name[node], 0) + 1); } } map[level[u]].put(name[u], map[level[u]].getOrDefault(name[u], 0) + 1); for (int i : queries[u]) { int l = queryLevels[i] + level[u]; if (l < n) ans[i] = map[l].size(); } if (keep == 0) { for (int i = tin[u]; i <= tout[u]; i++) { int node = vertex[i]; int l = level[node]; int occ = map[l].get(name[node]); if (occ == 1) map[l].remove(name[node]); else map[l].put(name[node], occ - 1); } } } static void dfs(int u, int l) { level[u] = l; vertex[time] = u; tin[u] = time++; biggest[u] = -1; size[u] = 1; for (int v : adjList[u]) { dfs(v, l + 1); size[u] += size[v]; if (biggest[u] == -1 || size[biggest[u]] < size[v]) biggest[u] = v; } tout[u] = time - 1; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≤ ri ≤ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≤ m ≤ 105) — the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≤ vi, ki ≤ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers — the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output