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
f746b6e28c003dd651c4767a660a9c41
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static ArrayList<Node>[] list; static Node[] edge; public static void main(String[] args){ Scan scan = new Scan(); int n = scan.nextInt(); int m = scan.nextInt(); list = new ArrayList[n]; // for(int i=0;i<n;i++) list[i] = new ArrayList<Node>(); edge = new Node[m]; for(int i=0;i<m;i++){ int u = scan.nextInt()-1; int v = scan.nextInt()-1; int w = scan.nextInt(); edge[i] = new Node(u, v, w); // list[u].add(edge[i]); } Arrays.sort(edge); int[] temp = new int[n]; int[] depth = new int[n]; int result = 0; for(int i=0;i<m;i++){ int j = i+1; while(j<m && edge[j].weight==edge[i].weight) j++; for(int k=i;k<j;k++){ Node now = edge[k]; if(depth[now.u]+1 > temp[now.v]){ temp[now.v] = depth[now.u]+1; } } for(int k=i;k<j;k++){ Node now = edge[k]; depth[now.v] = temp[now.v]; result = Math.max(result, depth[now.v]); } i = j-1; } System.out.println(result); } static class Node implements Comparable<Node>{ int u,v,weight; Node(int u, int v, int weight){ this.u = u; this.v = v; this.weight = weight; } @Override public int compareTo(Node o){ return Integer.compare(weight, o.weight); } } } class Scan implements Iterator<String>{ BufferedReader buffer; StringTokenizer tok; Scan(){ buffer = new BufferedReader(new InputStreamReader(System.in)); } @Override public boolean hasNext(){ while(tok==null || !tok.hasMoreElements()){ try{ tok = new StringTokenizer(buffer.readLine()); }catch(Exception e){ return false; } } return true; } @Override public String next(){ if(hasNext()) return tok.nextToken(); return null; } @Override public void remove(){ throw new UnsupportedOperationException(); } int nextInt(){ return Integer.parseInt(next()); } String nextLine(){ if(hasNext()) return tok.nextToken("\n"); return null; } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
0ef5994867146a4d458be26929d78a2a
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
/* Keep solving problems. */ import com.sun.javafx.geom.Edge; import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {1, 2, 1, 1}; int[] dy = {0, 0, -1, 1}; class Pair { int start; int end; public Pair(int start, int end) { this.start = start; this.end = end; } } void solve() throws IOException { int n = nextInt(); List<List<Pair>> edges = new ArrayList<>(); for (int i = 0; i < 100000 + 10; i++) { edges.add(new ArrayList<>()); } int m = nextInt(); for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = nextInt(); edges.get(w).add(new Pair(u, v)); } int[] dp = new int[n]; int[] tmp = new int[n]; for (int i = 1; i < edges.size(); i++) { List<Pair> es = edges.get(i); for (Pair p : es) { tmp[p.end] = 0; } for (Pair p : es) { tmp[p.end] = Math.max(tmp[p.end], 1 + dp[p.start]); } for (Pair p : es) { dp[p.end] = Math.max(dp[p.end], tmp[p.end]); } } int res = 0; for (int v : dp) { res = Math.max(res, v); } out(res); } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
f6676a8ea6911b859d91b254a2b49780
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final int mod = (int)1e9+7; static int max = (int)1e5 + 1; public static void main(String[] args) throws Exception { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); ArrayList<pair>[] e = new ArrayList[max]; for(int i = 1; i < max; i++) e[i] = new ArrayList(); while(m-- > 0) { int u = in.nextInt(); int v = in.nextInt(); int w = in.nextInt(); e[w].add(new pair(u, v)); } int[] dp = new int[n+1]; int[] tdp = new int[n+1]; int ans = 0; for(int i = 1; i < max; i++) { for(pair p : e[i]) tdp[p.s] = Math.max(tdp[p.s], dp[p.f] + 1); for(pair p : e[i]) { dp[p.s] = Math.max(dp[p.s], tdp[p.s]); tdp[p.s] = dp[p.s]; ans = Math.max(ans, dp[p.s]); } } out.print(ans); out.flush(); } static class pair { int f, s; public pair(int a, int b) { f = a; s = b; } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st == null || !st.hasMoreElements()) { 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(); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
403cf50f901067b20f23d745b68a96a5
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,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 s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} 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; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static class pair { int x; int y; public pair (int aa, int bb) { x = aa; y = bb; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; pair pair = (pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { return Objects.hash(x, y); } } public static void main(String args[])throws IOException { PrintWriter out=new PrintWriter(System.out); Reader sc=new Reader(); int n=sc.i(); int m=sc.i(); ArrayList<pair> al[]=new ArrayList[100001]; for(int i=0;i<=100000;i++)al[i]=new ArrayList(); for(int i=0;i<m;i++) { int a=sc.i(); int b=sc.i(); int w=sc.i(); al[w].add(new pair(a-1,b-1)); } int cache[]=new int[300001]; int temp[]=new int[300001]; for(int i=1;i<=100000;i++) { for(pair p:al[i]) temp[p.y]=0; for(pair p:al[i]) temp[p.y]=Math.max(temp[p.y],cache[p.x]+1); for(pair p:al[i]) cache[p.y]=Math.max(cache[p.y],temp[p.y]); } int max=0; for(int i=0;i<=300000;i++) max=Math.max(max,cache[i]); out.println(max); out.flush(); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
665f09c4836375a13a8069c01d068e78
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; Reader in = new Reader(); in.init(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { static class Node { int memo; int memoUpdate; List<Edge> adj = new ArrayList<Edge>(); } static class Edge { Node a; Node b; int cost; public Edge(Node a, Node b, int cost) { this.a = a; this.b = b; this.cost = cost; } } static class Graph { int nodeNumber; Node[] nodes; List<Edge> edges = new ArrayList<Edge>(); // O(nodeNumber) public Graph(int nodeNumber) { this.nodeNumber = nodeNumber; nodes = new Node[nodeNumber]; for (int i = 0; i < nodeNumber; ++i) { nodes[i] = new Node(); } } // O(1) public void addEdge(int a, int b, int cost) { Edge edge = new Edge(nodes[a], nodes[b], cost); nodes[a].adj.add(edge); edges.add(edge); } } Graph g; public void solve(int testNumber, Reader in, PrintWriter out) throws IOException { int N = in.nextInt(); int M = in.nextInt(); g = new Graph(N); for (int i = 0; i < M; ++i) { int a, b, c; a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); a--; b--; g.addEdge(a, b, c); } g.edges.sort(new Comparator<Edge>() { public int compare(Edge o1, Edge o2) { return Integer.compare(o1.cost, o2.cost); } }); for (Node node : g.nodes) { node.memo = 0; node.memoUpdate = 0; } for (int i = M-1; i >= 0; --i) { //out.println(i); Edge iEdge = g.edges.get(i); int j = i - 1; while(j >= 0 && g.edges.get(j).cost == iEdge.cost) j--; int nextI = j+1; for (j = nextI; j <= i; ++j) { Edge jEdge = g.edges.get(j); int lenNow = 1 + jEdge.b.memo; jEdge.a.memoUpdate = Math.max(jEdge.a.memoUpdate, lenNow); } // update... for (j = nextI; j <= i; ++j) { Edge jEdge = g.edges.get(j); jEdge.a.memo = jEdge.a.memoUpdate; } i = nextI; } int ans = 0; for (Node node : g.nodes) { ans = Math.max(ans, node.memo); } out.println(ans); } } class Reader { 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 double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
eee1c22d732350d48d6485de77aec0d7
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { public static void main(String[] args)throws IOException{ //Scanner sc = new Scanner(System.in); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String[] buf = reader.readLine().split(" "); int n = Integer.parseInt(buf[0]), m = Integer.parseInt(buf[1]); int[][] edge = new int[m][]; for(int i=0;i<m;i++) { buf = reader.readLine().split(" "); int u = Integer.parseInt(buf[0]), v = Integer.parseInt(buf[1]), w = Integer.parseInt(buf[2]); edge[i] = new int[]{u,v,w}; } Arrays.sort(edge,(a,b)->(b[2]-a[2])); int[] dp = new int[n+1]; int left = 0; while(left<m){ int right = left+1; while(right<m&&edge[right][2]==edge[left][2]) right++; HashMap<Integer,Integer> cur = new HashMap<>(); for(int idx=left;idx<right;idx++){ int key = edge[idx][0]; cur.put(key,Math.max(dp[edge[idx][1]]+1,cur.getOrDefault(key,0))); } for(int w:cur.keySet()) dp[w] = Math.max(cur.get(w),dp[w]); left = right; } int ans = 1; for(int i=1;i<=n;i++) ans = Math.max(ans,dp[i]); System.out.println(ans); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
d7abb972d2f6c9a492752c8d6b5f2716
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.sql.Array; import java.util.*; public class E { static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U,V>>{ public final U a; public final V b; private Pair(U a, V b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!a.equals(pair.a)) return false; return b.equals(pair.b); } @Override public int hashCode() { return 31 * a.hashCode() + b.hashCode(); } @Override public String toString() { return "(" + a + ", " + b + ")"; } @Override public int compareTo(Pair<U, V> o) { if(this.a.equals(o.a)){ return getV().compareTo(o.getV()); } return getU().compareTo(o.getU()); } private U getU() { return a; } private V getV() { return b; } static void print(Pair[] pairs){ for(int i=0;i<pairs.length;i++){ System.out.print(pairs[i]+" "); } System.out.println(); } static void print(Pair[][] pairs){ for(int i=0;i<pairs.length;i++){ for(int j=0;j<pairs[0].length;j++) { System.out.print(pairs[i] + " "); } System.out.println(); } } } static BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { String[] s1 = inp.readLine().split(" "); int v = Integer.parseInt(s1[0]); int m = Integer.parseInt(s1[1]); int[] dp = new int[v+1]; int[] simul = new int[v+1]; int[] val = new int[v+1]; int[] val1 = new int[v+1]; ArrayList<Pair<Integer,Pair<Integer,Integer>>> list = new ArrayList<>(); for(int i=0;i<m;i++){ s1 = inp.readLine().split(" "); int a = Integer.parseInt(s1[0]); int b = Integer.parseInt(s1[1]); int c = Integer.parseInt(s1[2]); list.add(new Pair<>(c,new Pair<>(a,b))); } Collections.sort(list); //System.out.println(list); int max = 0; for(int i=0;i<m;i+=0){ int a = list.get(i).a; ArrayList<Integer> list1 = new ArrayList<>(); while (i<m && list.get(i).a==a) { Pair<Integer,Pair<Integer,Integer>> pairPair = list.get(i); simul[pairPair.b.b] = Math.max(dp[pairPair.b.a] + 1,simul[pairPair.b.b]); list1.add(pairPair.b.b); i++; } //System.out.println(i); for(int j=0;j<list1.size();j++){ dp[list1.get(j)] = Math.max(simul[list1.get(j)],dp[list1.get(j)]); simul[list1.get(j)] = -1; max = Math.max(max, dp[list1.get(j)]); } } // print(dp); // print(val); out.write(max+"\n"); out.flush(); } static void print(int[] array){ for(int j=0;j<array.length;j++){ System.out.print(array[j]+" "); } System.out.println(); } static void print(int[][] array){ for(int i=0;i< array.length;i++) { for (int j = 0; j < array[0].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } } static void print(boolean[] array){ for(int j=0;j<array.length;j++){ System.out.print(array[j]+" "); } System.out.println(); } static void print(boolean[][] array){ for(int i=0;i< array.length;i++) { for (int j = 0; j < array[0].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } } static void print(long[] array){ for(int j=0;j<array.length;j++){ System.out.print(array[j]+" "); } System.out.println(); } static void print(long[][] array){ for(int i=0;i< array.length;i++) { for (int j = 0; j < array[0].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } } static void print(String[] array){ for(int j=0;j<array.length;j++){ System.out.print(array[j]+" "); } System.out.println(); } static void print(String[][] array){ for(int i=0;i< array.length;i++) { for (int j = 0; j < array[0].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
a1559961f4532e1210d982f9878f77ad
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class Abood3A { static int V, E, F[], T[], C[]; static int[] memo; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); V = sc.nextInt(); E = sc.nextInt(); F = new int[E]; T = new int[E]; C = new int[E]; for (int i = 0; i < E; ++i) { F[i] = sc.nextInt() - 1; T[i] = sc.nextInt() - 1; C[i] = sc.nextInt(); } memo = new int[V]; int ans = 0; Integer[] x = new Integer[E]; for (int i = 0; i < E; i++) { x[i] = i; } Arrays.sort(x, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return C[o2] - C[o1]; } }); for (int i = 0; i < E; ++i) { int j = i; ArrayList<Integer> t = new ArrayList<>(); ArrayList<Integer> v = new ArrayList<>(); for (j = i; j < E && C[x[j]] == C[x[i]] ; j++) { ans = Math.max(ans, Math.max(memo[F[x[j]]], memo[T[x[j]]] + 1)); t.add(F[x[j]]); v.add(Math.max(memo[F[x[j]]], memo[T[x[j]]] + 1)); } i = j - 1; for (int k = 0; k < t.size(); k++) memo[t.get(k)] = Math.max(memo[t.get(k)], v.get(k)); } out.println(ans); out.flush(); } 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
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
ade3f7e7f8aef2df4e7b0fd56bb6c51d
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); //Scanner sc = new Scanner(); Reader in = new Reader(); Main solver = new Main(); solver.solve(out, in); out.flush(); out.close(); } //<> static int maxn = (int)1e5*2; static long mod=(int)1e9+7; static int n,t,m,k; static Map<Integer,Integer> map; static int[] pre,suf,arr,freq,BIT; void solve(PrintWriter out, Reader in) throws IOException{ n = in.nextInt(); m = in.nextInt(); ArrayList<Edge> list = new ArrayList<>(); for(int i=0;i<m;i++) list.add(new Edge(in.nextInt(),in.nextInt(),in.nextInt())); Collections.sort(list); long[][] dp = new long[n+1][2]; LinkedList<Edge> relax = new LinkedList<>(); int prev=list.get(0).w,cnt=0; Edge e; for(int i=0;i<m;i++){ e = list.get(i); if(e.w!=prev) { cnt^=1; prev = e.w; while(relax.size()>0){ Edge temp = relax.remove(); dp[temp.v][cnt] = Math.max(dp[temp.v][0],dp[temp.v][1]); } relax.add(new Edge(0,e.v,0)); }else relax.add(new Edge(0,e.v,0)); if(dp[e.v][cnt] < dp[e.u][cnt^1]+1) dp[e.v][cnt] = dp[e.u][cnt^1]+1; } long ans = 0L; for(int i=1;i<=n;i++) ans = Math.max(ans,Math.max(dp[i][0],dp[i][1])); out.println(ans); } static class Edge implements Comparable<Edge> { int u,v,w; Edge(int u,int v,int w){ this.u = u; this.v = v; this.w = w; } public int compareTo(Edge o){ return this.w - o.w; } } 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
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
de2bc0ea9a52d515c192127a5c2f0650
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.*; import java.lang.*; public class TaskC implements Runnable { public void run() { InputReader c = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=c.nextInt(); pair[] a=new pair[n]; LinkedList<pair> qu=new LinkedList<>(); List<Integer>[] l=new ArrayList[n]; for(int i=0;i<n;i++) l[i] = new ArrayList<>(); for(int i=0;i<n;i++){ int deg=c.nextInt(); int s=c.nextInt(); a[i]=new pair(deg,s,i); if(deg==1) qu.add(a[i]); } edge[] ed=new edge[n]; int cnt=0; while (!qu.isEmpty()){ pair p=qu.remove(); if(p.x==0)continue; a[p.y].x--; a[p.y].y^=p.ind; if(a[p.y].x==1) qu.add(a[p.y]); ed[cnt++] = new edge(p.y,p.ind); } System.out.println(cnt); for(int i=0;i<cnt;i++){ System.out.println(ed[i].a+" "+ed[i].b); } w.close(); } class edge{ int a, b; public edge(int a,int b){ this.a=a;this.b=b; } } class pair{ int x,y; int ind; public pair(int a,int b,int c){ x=a; y=b; ind=c; } } class Graph{ private final int v; private List<List<Integer>> adj; Graph(int v){ this.v = v; adj = new ArrayList<>(v); for(int i=0;i<v;i++){ adj.add(new LinkedList<>()); } } private void addEdge(int a,int b){ adj.get(a).add(b); } private boolean isCyclic() { boolean[] visited = new boolean[v]; boolean[] recStack = new boolean[v]; for (int i = 0; i < v; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c: children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static class DJSet { public int[] upper; public DJSet(int n) { upper = new int[n]; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean equiv(int x, int y) { return root(x) == root(y); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; } return x == y; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } 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 TaskC(),"TaskC",1<<26).start(); } } /* BullPower BearPower FI CMO ChandelierExitL ATR RSI MACD pctB TEMA UBB LBB EMA of 22 Days MA for 22 days */
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
d8c3bd4b7dcac87ae1c40ca32e302e04
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; public class MishaAndForest implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int n = in.ni(); int[] degree = new int[n + 1], xor = new int[n + 1]; boolean[] processed = new boolean[n + 1]; Queue<Integer> queue = new ArrayDeque<>(); for (int i = 0; i < n; i++) { degree[i] = in.ni(); xor[i] = in.ni(); if (degree[i] == 1) { queue.add(i); } } List<String> result = new ArrayList<>(); while (queue.size() > 0) { int idx = queue.poll(); if (processed[idx]) continue; result.add(idx + " " + xor[idx]); int next = xor[idx]; degree[next]--; xor[next] ^= idx; if (degree[next] == 1) { queue.offer(next); } else if (degree[next] == 0) { processed[next] = true; } } out.println(result.size()); result.forEach(out::println); } @Override public void close() throws IOException { in.close(); out.close(); } 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 ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (MishaAndForest instance = new MishaAndForest()) { instance.solve(); } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
7aac100b339d75870336ed067bed6207
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.*; import java.io.*; public class MishaandForest { /************************ SOLUTION STARTS HERE ***********************/ static class Pair { int a , b; Pair(int a , int b){ this.a = a; this.b = b; } } private static void solve(FastScanner s1, PrintWriter out){ int N = s1.nextInt(); Pair arr[] = new Pair[N]; ArrayList<Pair> edges = new ArrayList<>(); for(int i=0;i<N;i++) arr[i] = new Pair(s1.nextInt(), s1.nextInt()); ArrayDeque<Integer> queue = new ArrayDeque<>(); for(int i=0;i<N;i++) if(arr[i].a == 1) queue.add(i); while(!queue.isEmpty()){ int curr = queue.remove(); if(arr[curr].a > 0){ Pair parent = arr[arr[curr].b]; parent.b ^= curr; parent.a--; edges.add(new Pair(curr, arr[curr].b)); if(parent.a == 1) queue.add(arr[curr].b); } } out.println(edges.size()); for(Pair p:edges) out.println(p.a + " " + p.b); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solve(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;} long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;} int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;} long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
0d1be4dd85bbd99c4ed9d05cfc2e0e29
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.List; public class Ada { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int n=sc.nextInt(); int s[]=new int[n]; int deg[]=new int[n]; LinkedList<Integer> q=new LinkedList<>(); for (int i=0;i<n;i++){ deg[i]=sc.nextInt(); s[i]=sc.nextInt(); if (deg[i]==1)q.add(i); } ArrayList<Integer> arr=new ArrayList<>(); while (!q.isEmpty()){ int u=q.remove(); if (deg[u]>=1) { int v = s[u]; arr.add(u); arr.add(v); deg[v]--; s[v] ^= u; if (deg[v] == 1) q.add(v); } } System.out.println(arr.size()/2); for (int i=0;i<arr.size();i+=2){ System.out.println(arr.get(i)+" "+arr.get(i+1)); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
7efb2cb5562e09cb8662e419f5060d5a
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; public class _Misha_and_Trees { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] deg = new int[n]; int[] xor = new int[n]; int[] addon = new int[n]; for (int i = 0; i < n; i++) { String[] sl = br.readLine().split(" "); deg[i] = Integer.parseInt(sl[0]); xor[i] = Integer.parseInt(sl[1]); } LinkedList<Integer> queue = new LinkedList<>(); for (int i = 0; i < n; i++) { if (deg[i] == 1) { queue.addLast(i); } } ArrayList<pair> st = new ArrayList<>(); while (queue.size() > 0) { int val = queue.removeFirst(); if(deg[val]==0){ continue; } int nbr = xor[val]; st.add(new pair(val, nbr)); deg[nbr]--; xor[nbr] = xor[nbr] ^ val; if (deg[nbr] == 1) { queue.addLast(nbr); } } StringBuilder sb = new StringBuilder(); sb.append(st.size()+"\n"); for (int i = 0; i < st.size(); i++) { pair sl = st.get(i); sb.append(sl.val1+" "+sl.val2+"\n") ; } System.out.println(sb); } public static class pair { int val1; int val2; pair(int s, int v) { this.val1 = s; this.val2 = v; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
97003265e4a0806833bb45c47ef1a7f2
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; import java.math.*; public class code { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[])throws IOException { FastReader scn = new FastReader(); int n = scn.nextInt(); Node[] nodes = new Node[n]; PriorityQueue<Node> pq = new PriorityQueue<Node>(); long no_edges = 0; for (int i = 0; i < n; i++) { int a = scn.nextInt(); int b = scn.nextInt(); no_edges = no_edges + a; nodes[i] = new Node(i, a, b); pq.add(nodes[i]); } boolean[] node_done = new boolean[n]; OutputStream out = new BufferedOutputStream(System.out); out.write(((no_edges / 2) + "\n").getBytes()); int count = 0; while (!pq.isEmpty()) { Node top = pq.poll(); if (node_done[top.index]) continue; if (top.degree == 0) { node_done[top.index] = true; } else if (top.degree == 1) { node_done[top.index] = true; count += 1; out.write((top.index + " " + top.xor_value + "\n").getBytes()); nodes[top.xor_value].degree = nodes[top.xor_value].degree - 1; nodes[top.xor_value].xor_value = nodes[top.xor_value].xor_value ^ top.index; pq.add(new Node(top.xor_value, nodes[top.xor_value].degree, nodes[top.xor_value].xor_value)); if (nodes[top.xor_value].degree == 0) node_done[top.xor_value] = true; } } assert(count == no_edges / 2); out.flush(); } } class Node implements Comparable<Node> { int index; int degree; int xor_value; public Node(int index, int degree, int xor_value) { this.index = index; this.degree = degree; this.xor_value = xor_value; } public int compareTo(Node n) { if (this.degree < n.degree) return -1; else if (this.degree == n.degree) return 0; else return 1; } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
cd716ce0e10b2ec05a7cae99290db37a
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; import java.math.*; public class code { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[])throws IOException { FastReader scn = new FastReader(); int n = scn.nextInt(); Node[] nodes = new Node[n]; PriorityQueue<Node> pq = new PriorityQueue<Node>(); long no_edges = 0; for (int i = 0; i < n; i++) { int a = scn.nextInt(); int b = scn.nextInt(); no_edges = no_edges + a; nodes[i] = new Node(i, a, b); pq.add(nodes[i]); } boolean[] node_done = new boolean[n]; OutputStream out = new BufferedOutputStream(System.out); out.write(((no_edges / 2) + "\n").getBytes()); while (!pq.isEmpty()) { Node top = pq.poll(); if (node_done[top.index]) continue; if (top.degree == 0) { node_done[top.index] = true; } else if (top.degree == 1) { node_done[top.index] = true; out.write((top.index + " " + top.xor_value + "\n").getBytes()); nodes[top.xor_value].degree = nodes[top.xor_value].degree - 1; nodes[top.xor_value].xor_value = nodes[top.xor_value].xor_value ^ top.index; pq.add(new Node(top.xor_value, nodes[top.xor_value].degree, nodes[top.xor_value].xor_value)); if (nodes[top.xor_value].degree == 0) node_done[top.xor_value] = true; } } out.flush(); } } class Node implements Comparable<Node> { int index; int degree; int xor_value; public Node(int index, int degree, int xor_value) { this.index = index; this.degree = degree; this.xor_value = xor_value; } public int compareTo(Node n) { if (this.degree < n.degree) return -1; else if (this.degree == n.degree) return 0; else return 1; } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
08cee0003d2662e71bfbb893bb09867a
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]){ Scanner s = new Scanner(System.in); int n= s.nextInt(); node[] u = new node[n]; list[] A = new list[2]; A[1]=new list(); A[0]=new list(); long m=0; for(int i=0;i<n;i++){ int x=s.nextInt(); m=m+x; int y=s.nextInt(); u[i]=new node(i,x,y); if(x==1)A[1].insert(u[i]); else if(x>1)A[0].insert(u[i]); } System.out.println(m/2); while(A[1].head!=null){ node a= A[1].head; int p=a.i; int q=a.x; A[1].delete(a); System.out.println(p+" "+q); u[q].d--; u[q].x=u[q].x^p; if(u[q].d==1){ A[1].insert(u[q]); A[0].delete(u[q]); } else if(u[q].d==0)A[1].delete(u[q]); } } public static class node{ public int d=0; public int i; public int x=0; public node prev=null; public node next=null; public node(int i,int d, int x) { super(); this.d = d; this.x=x; this.i=i; } public node getNext() { return next; } public void setNext(node next) { this.next = next; } public node getPrev() { return prev; } public void setPrev(node prev) { this.prev = prev; } } public static class list{ node head=null; public void insert(node u){ if(head==null){ head =u; } else{ node n = u; n.next=head; head.prev=n; head=n; head.prev=null; } } public void delete (node x){ if(x.prev!=null) x.prev.next=x.next; else{ head=x.next; if (head!=null)head.prev=null; } if(x.next!=null)x.next.prev=x.prev; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
491426fda69a4fd964bd7a4e13ae0de9
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner gimi = new Scanner(System.in); LinkedList<Integer> queue = new LinkedList<Integer>(); StringBuilder result = new StringBuilder(); int n = gimi.nextInt(); int[] indeg = new int[n]; int[] xorSum = new int[n]; for (int i = 0; i < n; i++) { indeg[i] = gimi.nextInt(); xorSum[i] = gimi.nextInt(); if (indeg[i] == 1) { queue.add(i); } } int count = 0; while (!queue.isEmpty()) { int current = queue.poll(); if (indeg[current] == 0) { continue; } int adjacent = xorSum[current]; xorSum[adjacent] ^= current; indeg[adjacent]--; if (indeg[adjacent] == 1) { queue.add(adjacent); } result.append(current).append(' ').append(adjacent).append('\n'); count++; } System.out.println(count); System.out.print(result); gimi.close(); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
2cc218c9a647a43c46a0c6a5c246fe4e
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class C { public static int cnt = 0; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); int[][] a = new int[n][2]; int[] s = new int[n]; int[] used = new int[n]; for (int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(in.readLine()); a[i][0] = Integer.parseInt(st.nextToken()); a[i][1] = i; used[i] = a[i][0]; s[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[] arg0, int[] arg1) { return arg0[0] - arg1[0]; } }); int[][] ans = new int[70000][2]; for (int i = 0; i < n; i++) { if (used[a[i][1]] == 1) { go(a[i][1], a, s, used, ans); } } out.println(cnt); for (int i = 0; i < cnt; i++) { out.println(ans[i][0] + " " + ans[i][1]); } in.close(); out.close(); } public static void go(int n, int[][] a, int[] s, int[] used, int[][] ans) { used[n] = 0; used[s[n]]--; s[s[n]] = s[s[n]] ^ n; ans[cnt][0] = n; ans[cnt][1] = s[n]; cnt++; if (used[s[n]] == 1) { go(s[n], a, s, used, ans); } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
b921a4ad89a5b2455f11a7ba12708ac1
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.awt.List; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; public class Watermelon { public static void main(String[] args) throws IOException{ Main m=new Main(); m.solve(); } } class Main{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private int[] array; private int[] tempMergArr; private int length; BigInteger[] temp=new BigInteger[31]; BigInteger x,y,z; StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } int[] marr=null; int[] BIT=new int[9]; int[] arr=null; int[][] lcsarr=null; void solve() throws IOException { int n=this.nextInt(); Count[] arr=new Count[n]; LinkedList<Count> pq=new LinkedList<>(); ArrayList<Count> list=new ArrayList<>(); for(int i=0;i<n;i++) { arr[i]=new Count(this.nextInt(),this.nextInt(),i); if(arr[i].i==1) pq.add(arr[i]); } // for(int i=0;i<pq.size();i++) // pq.get(i).display();; Count c=null; while(pq.size()!=0){ if(pq.getFirst().i==0) { pq.poll(); continue; } try{ list.add(new Count(pq.getFirst().k,pq.element().j,0)); arr[pq.getFirst().j].j^=(pq.element().k); arr[pq.getFirst().j].i--; c=arr[pq.getFirst().j]; }catch(Exception e){}try{ pq.removeFirst(); }catch(Exception e){} // Count[] darr=pq.toArray(new Count[pq.size()]); // for(int x=0;x<darr.length;x++) // darr[x].display(); // System.out.println(); if(c.i==1) pq.add(c); } System.out.println(list.size()); for(int i=0;i<list.size();i++){ list.get(i).display(); } } void recurs(int[] arr,int x){ } static int max_LIS=0; public int LIS(int[] arr,int n){ if(n==0) { marr[0]=1; return 1; } int current =1; for(int i=0;i<n;i++){ int subproblem=0; if(marr[i]==0) { subproblem=LIS(arr,i); marr[i]=subproblem; } else{ // System.out.println("Hey"); subproblem=marr[i]; } System.out.println(current+" "+subproblem+" "+i); if(arr[i]<arr[n]&&current<(1+subproblem)){ current=(1+subproblem); } } if(max_LIS<current) max_LIS=current; return current; } public int LCS1(int i,int j){ System.out.println(i+" "+j+"hey"); int n=0; if(i==-1||j==-1) return 0; if(arr[i]==marr[j]) n=1+LCS1(i-1,j-1); else{ n=Math.max(LCS1(i-1,j), LCS1(i,j-1)); } return n; } public int LCS(int i,int j){ System.out.println(i+" "+j); int n=0; if(i==-1||j==-1) return 0; if(arr[i]==marr[j]) { if(i!=0&&j!=0){ if(lcsarr[i-1][j-1]==0){ n=1+LCS(i-1,j-1); lcsarr[i-1][j-1]=n-1; } else{ n=1+lcsarr[i-1][j-1]; } } else n=1+LCS(i-1,j-1); } else{ int x,y=0; if(i!=0){ if(lcsarr[i-1][j]==-1) { x=LCS(i-1,j); lcsarr[i-1][j]=x; } else{ x=lcsarr[i-1][j]; } } else x=LCS(i-1,j); if(j!=0){ if(lcsarr[i][j-1]==-1){ y=LCS(i,j-1); lcsarr[i][j-1]=y; } else{ y=lcsarr[i][j-1]; } } else y=LCS(i,j-1); n=Math.max(x, y); } return n; } public BigInteger comb(int n,int r){ x=this.temp[n]; y=this.temp[r]; z=this.temp[n-r]; // System.out.println(x+" "+y+" "+z); BigInteger ret=x.divide(y.multiply(z)); return ret; } public void fact(){ this.temp[0]=BigInteger.ONE; this.temp[1]=BigInteger.ONE; for(int i=2;i<this.temp.length;i++){ temp[i]=(temp[i-1].multiply(BigInteger.valueOf(i))); } } private static int gcd(int a, int b) { while (b > 0) { int temp = b; b = a % b; // % is remainder a = temp; } return a; } private static int lcm(int a, int b) { return a * (b / gcd(a, b)); } static int[] toFractionPos(int x,int y){ int a=gcd(x,y); int[] arr={x/a,y/a}; //display(arr); return arr; } static void display(int[][] arr){ for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } System.out.println(); } static void display(String[] arr){ for(int i=0;i<arr.length;i++){ System.out.println(arr[i]+" "); } //System.out.println(); } static void display(int[] arr){ for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } static void display(double[] arr){ for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); } static void display(char[] arr){ // System.out.println(); int t=0; for(int i=0;i<arr.length;i++){ if(arr[i]!='0'){t=i;break;} } while(t!=arr.length){ System.out.print(arr[t]); t++; } System.out.println(); } static String str(char[] carr){ String str=""; for(int i=0;i<carr.length;i++){ str=str+carr[i]; } return str; } public void sort(int inputArr[]) { this.array = inputArr; this.length = inputArr.length; this.tempMergArr = new int[length]; doMergeSort(0, length - 1); } private void doMergeSort(int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; // Below step sorts the left side of the array doMergeSort(lowerIndex, middle); // Below step sorts the right side of the array doMergeSort(middle + 1, higherIndex); // Now merge both sides mergeParts(lowerIndex, middle, higherIndex); } } private void mergeParts(int lowerIndex, int middle, int higherIndex) { for (int i = lowerIndex; i <= higherIndex; i++) { tempMergArr[i] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (tempMergArr[i] <= tempMergArr[j]) { array[k] = tempMergArr[i]; i++; } else { array[k] = tempMergArr[j]; j++; } k++; } while (i <= middle) { array[k] = tempMergArr[i]; k++; i++; } } } class Count implements Comparable { Integer i; Integer j; Integer k; Count(int i,int j,int k){ this.i=i; this.j=j; this.k=k; } public Count() { // TODO Auto-generated constructor stub } void display(){ System.out.println(i+" "+j); } @Override public int compareTo(Object o) { // TODO Auto-generated method stub Count c=(Count)o; if(i.compareTo(c.i)>0) return 1; else if(i.compareTo(c.i)<0) return -1; else{ return 0; } } } class Counti implements Comparable { Integer i; int j; int k; Counti(int i,int j,int k){ this.j=j; this.i=i; this.k=k; } void display(){ System.out.println(i+" "+j); } @Override public int compareTo(Object o) { // TODO Auto-generated method stub Counti c=(Counti)o; if(i.compareTo(c.i)>0) return 1; else if(i.compareTo(c.i)<0) return -1; else return 0; } } class Extra{ ArrayList<Integer> list=new ArrayList<>(); Extra(int i){ } public Extra() { // TODO Auto-generated constructor stub } void display(){ System.out.print(list.size()+" "); for(int i=0;i<list.size();i++){ System.out.print(list.get(i)+" "); } System.out.println(); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
0a36759c720d7163328e1452a7273178
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.*; import java.util.*; public class Cf501C { public static void main(String args[]) throws IOException { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); Queue<Integer> q = new LinkedList<>(); List<String> ans = new ArrayList<>(); int sum[] = new int[n]; int deg[] = new int[n]; for (int i = 0; i < n; i++) { int d = in.nextInt(); int s = in.nextInt(); sum[i] = s; deg[i] = d; if(d == 1) q.add(i); } int count = 0; while(!q.isEmpty()){ int ver = q.poll(); if(deg[ver] == 0) continue; int par = sum[ver]; sum[par] ^= ver; ans.add(ver+" "+par); deg[ver]--; deg[par]--; if(deg[par] == 1) q.add(par); count++; } System.out.println(count); for(String x : ans){ System.out.println(x); } w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
341a969beb9f04eab67c13c096cb18d4
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
//package com.pb.codeforces.practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class CF501C { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] xor = new int[n]; int[] carr = new int[n]; HashSet<String> set = new HashSet<String>(); Queue<Integer> q = new LinkedList<Integer>(); for(int i=0; i<n; i++) { int cnt = in.nextInt(); int xVal = in.nextInt(); carr[i] = cnt; xor[i] = xVal; if(cnt == 1) q.add(i); } while(!q.isEmpty()) { int id = q.poll(); if(carr[id] != 1) continue; if(id > xor[id]) set.add(id+" "+xor[id]); else set.add(xor[id]+" "+id); xor[xor[id]] ^= id; carr[xor[id]]--; if(carr[xor[id]] == 1) q.add(xor[id]); } out.println(set.size()); for(String s : set) out.println(s); out.close(); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
0f739f2ed02e35271ffc6cf4cbd96315
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); Task501C solver = new Task501C(); solver.solve(1, in, out); out.close(); } static class Task501C { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int arr[] = new int[n]; int xor[] = new int[n]; int vis[] = new int[n]; int i; Queue<Integer> q = new LinkedList<>(); ArrayList<Integer> u = new ArrayList<>(); ArrayList<Integer> v = new ArrayList<>(); for (i = 0; i < n; i++) { arr[i] = in.nextInt(); xor[i] = in.nextInt(); if (arr[i] == 1) q.offer(i); } i = 0; while (!q.isEmpty()) { int k = q.poll(); if (vis[k] == 1) continue; u.add(k); v.add(xor[k]); xor[xor[k]] ^= k; arr[xor[k]]--; if (arr[xor[k]] == 1) q.offer(xor[k]); if (arr[xor[k]] == 0) vis[xor[k]] = 1; i++; } out.println(u.size()); for (i = 0; i < u.size(); i++) out.println(u.get(i) + " " + v.get(i)); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
0db964d11fa66ace6d04c588036980fd
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
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; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeMap; /** * Hello world! * */ public class App { private static int[] tree; private static int[] degree; private static Queue<Integer> leaves = new LinkedList<>(); public static void main(String[] args) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String[] line; line = reader.readLine().split(" "); int n = Integer.parseInt(line[0]); tree = new int[n]; degree = new int[n]; for (int i = 0; i < n; ++i) { line = reader.readLine().split(" "); int currDegree = Integer.parseInt(line[0]); int xorSum = Integer.parseInt(line[1]); degree[i] = currDegree; tree[i] = xorSum; if (degree[i] == 1) { leaves.add(i); } } Set<String> res = new HashSet<>(); while (!leaves.isEmpty()) { int leaf = leaves.remove(); int parent = tree[leaf]; res.add(leaf < parent ? leaf + " " + parent : parent + " " + leaf); if (degree[parent] > 1) { tree[parent] ^= leaf; if (--degree[parent] == 1) { leaves.add(parent); } } } System.out.println(res.size()); for (String s : res) { System.out.println(s); } } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
b8ebb61838ee811e0d7232d997596d11
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); int[]deg=new int[n]; int[]xor=new int[n]; Queue<Integer>q=new LinkedList<>(); ArrayList<String>ans=new ArrayList<>(); boolean vis[]=new boolean[n]; for(int i=0;i<n;i++) { deg[i]=ni(); if(deg[i]==1) q.add(i); xor[i]=ni(); } while(!q.isEmpty()) { int from=q.poll(); if(deg[from]==0) vis[from]=true; if(vis[from]) continue; int to=xor[from]; xor[to]^=from; xor[from]=0; deg[to]--; ans.add(new String(from+" "+to)); if(deg[to]==1) q.add(to); } pn(ans.size()); for(int i=0;i<ans.size();i++) pn(ans.get(i)); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-->0) {process();} out.flush();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);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 int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} 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 class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
6c3be5f1d974c8bccb8902c22cc2021d
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kanak893 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader fi, PrintWriter out) { int n = fi.nextInt(); int degree[] = new int[n]; int xor[] = new int[n]; int i, j, edges; StringBuilder sb = new StringBuilder(""); edges = 0; Queue<Node> queue = new LinkedList<>(); for (i = 0; i < n; i++) { degree[i] = fi.nextInt(); xor[i] = fi.nextInt(); if (degree[i] == 1) { queue.add(new Node(i, degree[i], xor[i])); } } while (!queue.isEmpty()) { Node x = queue.poll(); int index = x.index; if (degree[index] == 1) { degree[index]--; int t = xor[index]; xor[t] = xor[t] ^ index; degree[t]--; sb.append(index + " " + t + "\n"); edges++; if (degree[t] == 1) { queue.add(new Node(t, degree[t], xor[t])); } } } out.println(edges); out.println(sb.toString()); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Node { int index; int degree; int xor; Node(int index, int degree, int xor) { this.index = index; this.degree = degree; this.xor = xor; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
b9716393c0996ee0301203aa6582c529
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class C { static class Node implements Comparable<Node>{ int n; int degree; int sum; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return n == node.n; } @Override public int hashCode() { return n; } public Node(int n, int degree, int sum) { this.degree = degree; this.sum = sum; this.n = n; } @Override public int compareTo(Node o) { if (this.degree < o.degree) { return -1; } else if (this.degree == o.degree) { if (this.n < o.n) { return -1; } else if (this.n == o.n) { return 0; } else { return 1; } } else { return 1; } } } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); TreeSet<Node> q = new TreeSet<>(); int[] degrees = new int[n]; int[] sums = new int[n]; long total = 0; for (int i = 0; i < n; ++i) { int degree = sc.nextInt(); int sum = sc.nextInt(); q.add(new Node(i, degree, sum)); degrees[i] = degree; sums[i] = sum; total += degree; } out.println(total / 2); while(q.size() > 0) { Node node = q.pollFirst(); int thisNode = node.n; if (degrees[thisNode] == 0) { continue; } if (degrees[thisNode] == 1) { int otherNode = sums[thisNode]; out.format("%s %s\n", thisNode, otherNode); sums[otherNode] ^= thisNode; q.remove(new Node(otherNode, degrees[otherNode], 1)); degrees[otherNode] -= 1; q.add(new Node(otherNode, degrees[otherNode], sums[otherNode])); } else { out.println("hoooww"); } } out.close(); } public static PrintWriter out; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
349f1e54e9bc701bc2ad1416a4f43120
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.LinkedList; import java.util.Arrays; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.AbstractSequentialList; import java.io.BufferedReader; import java.util.AbstractQueue; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.PriorityQueue; import java.io.IOException; import java.util.AbstractCollection; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Vertex implements Comparable { public int number; public int edges; public Vertex(int number, int edges) { this.number = number; this.edges = edges; } public int compareTo(Object o) { if(((Vertex)o).edges > this.edges) return -1; else if(((Vertex)o).edges < this.edges) return 1; // else if(((Vertex)o).number < this.number) // return -1; // else return 1; return 0; } public boolean equals(Object obj) { if(number == ((Vertex)obj).number && edges == ((Vertex)obj).edges) return true; else return false; } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int d[] = new int[n + 2]; int s[] = new int[n + 2]; int used[] = new int[n + 2]; Arrays.fill(used, 0); long t = 0; ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>(); PriorityQueue<Vertex> q = new PriorityQueue<Vertex>(); for(int i = 0; i < n; i++) { graph.add(new LinkedList<Integer>()); d[i] = in.nextInt(); t += d[i]; s[i] = in.nextInt(); Vertex v = new Vertex(i, d[i]); q.add(v); } Vertex v; int to; while(!q.isEmpty()) { v = q.remove(); to = s[v.number]; if(v.edges != 1 || to == v.number || used[v.number] == 1) { continue; } graph.get(v.number).add(to); // q.remove(new Vertex(to, d[to])); d[to]--; if(d[to] == 0) used[to] = 1; s[to] ^= v.number; q.add(new Vertex(to, d[to])); } out.println(t / 2); for(int i = 0; i < n; i++) { LinkedList l = graph.get(i); Iterator it = l.iterator(); while(it.hasNext()) { out.println(i + " " + it.next()); } } } } 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
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
1888006bd47d022346206b1b40b9b774
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class cSolution{ private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[]){ solve(); } private static void solve(){ int n = Integer.parseInt(next()); Note[] vertices = new Note[n]; PriorityQueue<Note> queue = new PriorityQueue<Note>(); Note curr; int d, x; for (int i = 0; i < n; i++){ d = Integer.parseInt(next()); x = Integer.parseInt(next()); curr = new Note(d, x, i); vertices[i] = curr; if (d == 1){ queue.add(curr); } } int edgeCount = 0; int[][] edges = new int[n-1][2]; Note next; while(queue.size() > 0){ next = queue.peek(); if (next.degree != 0){ edges[edgeCount][0] = next.index; edges[edgeCount][1] = next.xorsum; vertices[next.xorsum].tickDegree(); vertices[next.xorsum].fixXorSum(next.index); if (vertices[next.xorsum].degree == 1){ queue.add(vertices[next.xorsum]); } edgeCount += 1; } queue.remove(next); } System.out.println(edgeCount); for (int i = 0; i < edgeCount; i++){ System.out.println(edges[i][0] + " " + edges[i][1]); } } private static StringTokenizer st; private static String next(){ while (st == null || !st.hasMoreElements()){ String str; try{ str = br.readLine(); } catch (IOException e){ return null; } st = new StringTokenizer(str); } return st.nextToken(); } static class Note implements Comparable<Note>{ public int degree; public int xorsum; public int index; public Note(int d, int x, int i){ degree = d; xorsum = x; index = i; } @Override public int compareTo(Note other){ return Integer.compare(degree, other.degree); } public void tickDegree(){ degree--; } public void fixXorSum(int x){ xorsum = xorsum ^ x; } } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
7c37236c8803c04bba225ffcc5fda342
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import java.text.*; public class Rough{ static PrintWriter w=new PrintWriter(System.out); public static void main(String [] args){ DecimalFormat dm=new DecimalFormat("0.000000"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int deg[]=new int[n]; int xor[]=new int[n]; Queue<Integer> q=new LinkedList<Integer>(); for(int i=0;i<n;i++){ deg[i]=sc.nextInt(); xor[i]=sc.nextInt(); if(deg[i]==1){ q.add(i); } } int j=0; int ans[][]=new int[n][2]; while(!q.isEmpty()){ int a=q.poll(); if(deg[a]==0){ continue; } deg[a]--; int adj=xor[a]; xor[adj]=xor[adj]^a; deg[adj]--; if(deg[adj]==1) q.add(adj); ans[j][0]=a; ans[j++][1]=adj; } w.println(j); for(int i=0;i<j;i++){ w.println(ans[i][0]+" "+ans[i][1]); } w.close(); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
90b2063e42afdf7630c2af6590bf774f
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class C501 { public static BufferedReader in; public static PrintWriter out; public static StringTokenizer tokenizer; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; in = new BufferedReader(new InputStreamReader(inputStream), 32768); out = new PrintWriter(outputStream); solve(); out.close(); } static class Edge { int x, y; Edge(int x, int y) { this.x = x; this.y = y; } } public static void solve() { int n = nextInt(); int[] degree = new int[n]; int[] xor = new int[n]; Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { degree[i] = nextInt(); xor[i] = nextInt(); if (degree[i] == 1) { q.add(i); } } ArrayList<Edge> edges = new ArrayList<Edge>(); while (!q.isEmpty()) { int v = q.poll(); if (degree[v] == 0) { continue; } degree[xor[v]]--; xor[xor[v]] ^= v; edges.add(new Edge(v, xor[v])); if (degree[xor[v]] == 1) { q.add(xor[v]); } } out.println(edges.size()); for (Edge e : edges) { out.println(e.x + " " + e.y); } } public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
d3b79f8352fad720674450c3ba5dff80
train_002.jsonl
1421053200
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; void solve() throws IOException { int n = nextInt(); int[] degree = new int[n]; int[] sum = new int[n]; for (int i = 0; i < n; i++) { degree[i] = nextInt(); sum[i] = nextInt(); } Deque<Integer> deck = new LinkedList<>(); List<String> res = new ArrayList<>(); for (int i = 0; i < n; i++) { if (degree[i] == 1) { deck.addLast(i); } } while (!deck.isEmpty()) { int cur = deck.removeFirst(); int to = sum[cur]; if (degree[to] == 0 || degree[cur] == 0) { continue; } degree[to]--; sum[to] ^= cur; res.add(cur + " " + to); if (degree[to] == 1) { deck.addLast(to); } } outln(res.size()); for (int i = 0; i < res.size(); i++) { outln(res.get(i)); } } int[][] transpose(int[][] mat) { int n = mat.length; int m = mat[0].length; int[][] res = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { res[j][i] = mat[i][j]; } } return res; } void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
1 second
["2\n1 0\n2 0", "1\n0 1"]
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "trees" ]
14ad30e33bf8cad492e665b0a486008e
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si &lt; 216), separated by a space.
1,500
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
standard output
PASSED
a3daa2fcf4b12a52398d3e037246fa46
train_002.jsonl
1562942100
There are $$$n$$$ points on the plane, the $$$i$$$-th of which is at $$$(x_i, y_i)$$$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.The strange area is enclosed by three lines, $$$x = l$$$, $$$y = a$$$ and $$$x = r$$$, as its left side, its bottom side and its right side respectively, where $$$l$$$, $$$r$$$ and $$$a$$$ can be any real numbers satisfying that $$$l &lt; r$$$. The upper side of the area is boundless, which you can regard as a line parallel to the $$$x$$$-axis at infinity. The following figure shows a strange rectangular area. A point $$$(x_i, y_i)$$$ is in the strange rectangular area if and only if $$$l &lt; x_i &lt; r$$$ and $$$y_i &gt; a$$$. For example, in the above figure, $$$p_1$$$ is in the area while $$$p_2$$$ is not.Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // public class cf1190d { public static void main(String[] args) throws IOException { int n = ri(); bit bit = new bit(n, Long::sum); Map<Integer, Integer> idx = new TreeMap<>(), idy = new TreeMap<>(), cntx = new TreeMap<>(); int tot = 0; List<List<Integer>> x = new ArrayList<>(); List<Integer> y = new ArrayList<>(); for (int i = 0; i < n; ++i) { x.add(new ArrayList<>()); } for (int i = 0; i < n; ++i) { int px = rni(), py = ni(); if (!idy.containsKey(py)) { idy.put(py, tot++); y.add(py); } x.get(idy.get(py)).add(px); cntx.put(px, cntx.getOrDefault(px, 0) + 1); } tot = 0; for (int key : cntx.keySet()) { idx.put(key, ++tot); bit.upd(tot, 1); } y.sort(Integer::compareTo); long ans = 0; for (int py : y) { x.get(idy.get(py)).sort(Integer::compareTo); int pre = 1; for (int px : x.get(idy.get(py))) { // prln(bit.qry(pre, idx.get(px)), bit.qry(idx.get(px), tot)); ans += bit.qry(pre, idx.get(px)) * bit.qry(idx.get(px), tot); pre = idx.get(px) + 1; if (cntx.containsKey(px)) { cntx.put(px, cntx.get(px) - 1); if (cntx.get(px) == 0) { cntx.remove(px); bit.upd(idx.get(px), -1); } } } } prln(ans); close(); } @FunctionalInterface interface LongOperator { long merge(long a, long b); } static class bit { LongOperator op; int n; long bit[]; bit(int size, LongOperator operator) { bit = new long[(n = size) + 1]; op = operator; } bit(long[] arr, LongOperator operator) { bit = new long[(n = arr.length + 1)]; op = operator; for (int i = 0; i < n - 1; ++i) upd(i, arr[i]); ++n; } void upd(int i, long x) { while (i <= n) { bit[i] = op.merge(bit[i], x); i += i & (-i); } } long qry(int i) { long ans = 0; while (i > 0) { ans = op.merge(ans, bit[i]); i -= i & (-i); } return ans; } long qry(int l, int r) { return qry(r) - qry(l - 1); } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n1 1\n1 2\n1 3", "3\n1 1\n2 1\n3 1", "4\n2 1\n2 2\n3 1\n3 2"]
3 seconds
["3", "6", "6"]
NoteFor the first example, there is exactly one set having $$$k$$$ points for $$$k = 1, 2, 3$$$, so the total number is $$$3$$$.For the second example, the numbers of sets having $$$k$$$ points for $$$k = 1, 2, 3$$$ are $$$3$$$, $$$2$$$, $$$1$$$ respectively, and their sum is $$$6$$$.For the third example, as the following figure shows, there are $$$2$$$ sets having one point; $$$3$$$ sets having two points; $$$1$$$ set having four points. Therefore, the number of different non-empty sets in this example is $$$2 + 3 + 0 + 1 = 6$$$.
Java 11
standard input
[ "data structures", "two pointers", "sortings", "divide and conquer" ]
a45a5a4b95f97a49960bc86953dd8723
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \times 10^5$$$) — the number of points on the plane. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \leq x_i, y_i \leq 10^9$$$) — the coordinates of the $$$i$$$-th point. All points are distinct.
2,000
Print a single integer — the number of different non-empty sets of points she can obtain.
standard output
PASSED
c36d11386cc3efe0647b890a589ecb62
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class OptimalNumberPermutation { public static void main(String[] args) { Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); if(n%2 == 0){ for(int i = 1; i < n; i += 2) out.print(i+" "); for(int i = n-1; i >= 1; i-= 2) out.print(i+" "); for(int i = 2; i < n; i+=2)out.print(i+" "); out.print(n+" "); for(int i = n-2; i >= 2; i-=2)out.print(i+" "); out.println(n); } else { for(int i = 1; i < n; i+= 2) out.print(i+" "); out.print(n+" "); for(int i = n-2; i >= 1; i -= 2) out.print(i+" "); for(int i = 2; i < n; i+= 2) out.print(i+" "); for(int i = n-1; i >= 2; i -= 2) out.print(i+" "); out.println(n); } out.close(); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
6283b36fe3e73beff09c6c40b03b5902
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; public class Solution1 implements Runnable { static final long MAX = 1000000007L; 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 Solution1(),"Solution1",1<<26).start(); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } // method to return LCM of two numbers long lcm(long a, long b) { return (a*b)/gcd(a, b); } int root(int a){ while(arr[a] != a){ arr[a] = arr[arr[a]]; a = arr[a]; } return a; } void union(int a,int b){ int xroot = root(a); int yroot = root(b); if(arr[xroot] < arr[yroot]){ arr[xroot] = yroot; }else{ arr[yroot] = xroot; } } boolean find(int a,int b){ int roota = root(a); int rootb = root(b); if(roota == rootb){ return true; }else{ return false; } } int[] arr; final int level = 20; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); int[] ans = new int[2*n + 1]; Arrays.fill(ans,-1); int j = 1; for(int i = 1;i <= n;i += 2){ ans[j] = i; ans[n - j + 1] = i; j++; } j = n + 1; for(int i = 2;i <= n;i+=2){ ans[j] = i; ans[j + n - i] = i; j++; } for(int i = 1;i <= 2*n;i++){ if(ans[i] == -1){ ans[i] = n; } } for(int i = 1;i <= 2*n;i++){ w.print(ans[i] + " "); } w.close(); } static class Pair implements Comparable<Pair>{ int a; int b; long c; Pair(){} Pair(int a,int b,long c){ this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p){ return Long.compare(this.c,p.c); } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
3c3c0a3c90d0ba013337fe346e2dcb3c
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 998244353; long fac[]= new long[3000]; public void solve() throws IOException { int n = readInt(); if((n%2)==0) { ArrayList <Integer> val = new ArrayList<>(); for(int i =1;i<=n;i=i+2) val.add(i); for(int i=n-1;i>=1;i=i-2) val.add(i); for(int i=2;i<=n;i=i+2) val.add(i); for(int i=n-2;i>=2;i=i-2) val.add(i); val.add(n); for(int j=0;j<val.size();j++) out.print(val.get(j)+" "); } else { ArrayList <Integer> val = new ArrayList<>(); for(int i =1;i<=n;i=i+2) val.add(i); for(int i=n-2;i>=1;i=i-2) val.add(i); for(int i=2;i<=n;i=i+2) val.add(i); for(int i=n-1;i>=2;i=i-2) val.add(i); val.add(n); for(int j=0;j<val.size();j++) out.print(val.get(j)+" "); } } public int build(int seg[] , int left, int right , int index , int sum[]) { if(left==right) { seg[index]= sum[left]; return seg[index]; } int mid = left +(right-left)/2; int left1 = build(seg, left,mid,2*index+1,sum); int right1 = build(seg,mid+1,right, 2*index+2,sum); seg[index]=Math.max(left1,right1); return seg[index]; } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int val ; int color; edge(int u, int v) { this.val=u; this.color=v; } public int compareTo(edge e) { return this.val-e.val; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
3728dbfbb9e07ebd7bfe44ff25a744c1
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; /** * * @author Sourav Kumar Paul */ public class SolveDD { public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(reader.readLine()); int arr[] = new int[2*n]; for(int i=1, pos=0; i<n; i+=2) { arr[pos] = i; arr[n-pos-1] = i; pos++; } for(int i=2, pos = 0; i<n; i+=2) { arr[n + pos] = i; arr[2*n - pos - 2] = i; pos++; } for(int i=0; i<2*n; i++) { if(arr[i] != 0) out.print(arr[i]+" "); else out.print(n +" "); } out.flush(); out.close(); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
48c7f2a2af44cd9f01ce60c7a5ccbcbf
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Div2_622D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] solution = solve(n); StringBuilder answer = new StringBuilder(Integer.toString(solution[0])); for(int i=1;i<solution.length;i++) { answer.append(' ').append(solution[i]); } System.out.println(answer.toString()); } public static int[] solve(int n) { int[] solution = new int[2*n]; int index = 0; int i; for(i=1;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 1) solution[index++]=n; for(i=i-2;i>0;i-=2) { solution[index++] = i; } for(i=2;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 0) solution[index++]=n; for(i = i-2;i>0;i-=2) { solution[index++] = i; } solution[index++] = n; return solution; } public static int getScore(int[] arr) { HashMap<Integer,Integer> lookup = new HashMap<>(); int sum = 0; int n = arr.length/2; for(int j=0;j<arr.length;j++) { if(lookup.containsKey(arr[j])) { // sum sum += (n-arr[j]) * Math.abs(Math.abs(lookup.get(arr[j]) - j) + arr[j] - n); } else { lookup.put(arr[j], j); } } return sum; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
c429d67cd960686fc944e5548dd61df3
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Div2_622D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] solution = solve(n); PrintWriter out = new PrintWriter(System.out, false); out.print(solution[0]); for(int i=1;i<solution.length;i++) { out.print(' '); out.print(solution[i]); } out.flush(); } public static int[] solve(int n) { int[] solution = new int[2*n]; int index = 0; int i; for(i=1;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 1) solution[index++]=n; for(i=i-2;i>0;i-=2) { solution[index++] = i; } for(i=2;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 0) solution[index++]=n; for(i = i-2;i>0;i-=2) { solution[index++] = i; } solution[index++] = n; return solution; } public static int getScore(int[] arr) { HashMap<Integer,Integer> lookup = new HashMap<>(); int sum = 0; int n = arr.length/2; for(int j=0;j<arr.length;j++) { if(lookup.containsKey(arr[j])) { // sum sum += (n-arr[j]) * Math.abs(Math.abs(lookup.get(arr[j]) - j) + arr[j] - n); } else { lookup.put(arr[j], j); } } return sum; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
938e3fb9b5f8cec11e00de91e32d1eba
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Div2_622D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] solution = solve(n); PrintWriter out = new PrintWriter(System.out); out.print(solution[0]); for(int i=1;i<solution.length;i++) { out.print(' '); out.print(solution[i]); } out.flush(); } public static int[] solve(int n) { int[] solution = new int[2*n]; int index = 0; int i; for(i=1;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 1) solution[index++]=n; for(i=i-2;i>0;i-=2) { solution[index++] = i; } for(i=2;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 0) solution[index++]=n; for(i = i-2;i>0;i-=2) { solution[index++] = i; } solution[index++] = n; return solution; } public static int getScore(int[] arr) { HashMap<Integer,Integer> lookup = new HashMap<>(); int sum = 0; int n = arr.length/2; for(int j=0;j<arr.length;j++) { if(lookup.containsKey(arr[j])) { // sum sum += (n-arr[j]) * Math.abs(Math.abs(lookup.get(arr[j]) - j) + arr[j] - n); } else { lookup.put(arr[j], j); } } return sum; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
d6030c074eddf02e3e1dc735f04d8f88
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Div2_622D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] solution = solve(n); StringBuilder answer = new StringBuilder(Integer.toString(solution[0])); for(int i=1;i<solution.length;i++) { answer.append(' ').append(solution[i]); } System.out.println(answer.toString()); } public static int[] solve(int n) { int[] solution = new int[2*n]; int index = 0; int i; for(i=1;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 1) solution[index++]=n; for(i=i-2;i>0;i-=2) { solution[index++] = i; } for(i=2;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 0) solution[index++]=n; for(i = i-2;i>0;i-=2) { solution[index++] = i; } solution[index++] = n; return solution; } public static int getScore(int[] arr) { HashMap<Integer,Integer> lookup = new HashMap<>(); int sum = 0; int n = arr.length/2; for(int j=0;j<arr.length;j++) { if(lookup.containsKey(arr[j])) { // sum sum += (n-arr[j]) * Math.abs(Math.abs(lookup.get(arr[j]) - j) + arr[j] - n); } else { lookup.put(arr[j], j); } } return sum; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
a9d377d5ad1c188b56db37798c12e2d0
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class Div2_622D { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); StringBuilder answer = new StringBuilder(); for(int num : solve(n)) { answer.append(num).append(' '); } System.out.println(answer.toString().trim()); } public static int[] solve(int n) { int[] solution = new int[2*n]; int index = 0; int i; for(i=1;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 1) solution[index++]=n; for(i=i-2;i>0;i-=2) { solution[index++] = i; } for(i=2;i<n;i+=2) { solution[index++] = i; } if(n % 2 == 0) solution[index++]=n; for(i = i-2;i>0;i-=2) { solution[index++] = i; } solution[index++] = n; return solution; } public static int getScore(int[] arr) { HashMap<Integer,Integer> lookup = new HashMap<>(); int sum = 0; int n = arr.length/2; for(int j=0;j<arr.length;j++) { if(lookup.containsKey(arr[j])) { // sum sum += (n-arr[j]) * Math.abs(Math.abs(lookup.get(arr[j]) - j) + arr[j] - n); } else { lookup.put(arr[j], j); } } return sum; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
dde9d9fa28196097c3cbff895826c634
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
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 D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); StringBuilder s = new StringBuilder(); int n = sc.nextInt(), a[] = new int[n<<1]; Arrays.fill(a, n); for(int k = 0, i = 2; n - i > 0; i +=2, ++k) a[k] = a[k + n - i] = i; for(int k = 2 * n - 1, i = 1; n - i > 0; i += 2, --k) a[k] = a[k - n + i] = i; for(int i = 0; i < 2 * n - 1; ++i) s.append(a[i] + " "); s.append(a[2*n - 1]); out.println(s); out.flush(); out.close(); } // 2 4 4 2 1 3 5 5 3 1 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"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
5d9c042da5f0839125ce2f2d02b94d9f
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P622D { int n, n2; int [] a = null; BitSet p = null; boolean doit(int num) { if (num == n) { return true; } for (int pi = p.nextClearBit((num & 1) * n + num / 2), l = (n - num); pi < (n2 - l); pi = p.nextClearBit(pi + 1)) { if (!p.get(pi + l)) { a[pi] = a[pi + l] = num; p.set(pi); p.set(pi + l); if (doit(num + 1)) { return true; } a[pi] = a[pi + l] = 0; p.clear(pi); p.clear(pi + l); } } return false; } public void run() throws Exception { n2 = (n = nextInt()) * 2; a = new int [n2]; p = new BitSet(n2); doit(1); for (int i = 0; i < n2; i++) { print(((a[i] != 0) ? a[i] : n) + " "); } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P622D().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
b359e659f6c1fada2f428a69aa05679a
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P622D { public void run() throws Exception { int n = nextInt(); int [] a = new int [n << 1]; for (int i = 1; i < n; i++) { a[(i & 1) * n + i / 2] = a[(i & 1) * n + i / 2 + n - i] = i; } for (int i = 0; i < (n * 2); i++) { print(((a[i] != 0) ? a[i] : n) + " "); } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P622D().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
fe223ec58cca123ba2e1962905e19f54
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * * @author Saju * */ public class Main { private static int dx[] = { 1, 0, -1, 0 }; private static int dy[] = { 0, -1, 0, 1 }; private static final long INF = Long.MAX_VALUE; private static final int INT_INF = Integer.MAX_VALUE; private static final long NEG_INF = Long.MIN_VALUE; private static final int NEG_INT_INF = Integer.MIN_VALUE; private static final double EPSILON = 1e-10; private static final long MAX = (long) 1e12; private static final long MOD = 100000007; private static final int MAXN = 300005; private static final int MAXA = 1000007; private static final int MAXLOG = 22; private static final double PI = Math.acos(-1); public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new FileInputStream("src/test.in")); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out"))); /* */ int n = in.nextInt(); int arr[] = new int[(2 * n) + 1]; int j = 1; for(int i = 1; i <= n; i += 2) { int di = n - i; arr[j] = i; arr[j + di] = i; j++; if(di == 0) { arr[2 * n] = i; } } j = n + 1; for(int i = 2; i <= n; i += 2) { int di = n - i; arr[j] = i; arr[j + di] = i; j++; if(di == 0) { arr[2 * n] = i; } } // System.out.println(Arrays.toString(arr)); for(int i = 1; i <= 2 * n; i++) { out.print(arr[i] + " "); } in.close(); out.flush(); out.close(); System.exit(0); } /* * return the number of elements in list that are less than or equal to the val */ private static long upperBound(List<Long> list, long val) { int start = 0; int len = list.size(); int end = len - 1; int mid = 0; while (true) { if (start > end) { break; } mid = (start + end) / 2; long v = list.get(mid); if (v == val) { start = mid; while(start < end) { mid = (start + end) / 2; if(list.get(mid) == val) { if(mid + 1 < len && list.get(mid + 1) == val) { start = mid + 1; } else { return mid + 1; } } else { end = mid - 1; } } return start + 1; } if (v > val) { end = mid - 1; } else { start = mid + 1; } } if (list.get(mid) < val) { return mid + 1; } return mid; } private static boolean isPalindrome(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); String str1 = sb.reverse().toString(); return str.equals(str1); } private static String getBinaryStr(long n, int j) { String str = Long.toBinaryString(n); int k = str.length(); for (int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } private static long modInverse(long r) { return bigMod(r, MOD - 2, MOD); } private static long bigMod(long n, long k, long m) { long ans = 1; while (k > 0) { if ((k & 1) == 1) { ans = (ans * n) % m; } n = (n * n) % m; k >>= 1; } return ans; } private static long ceil(long n, long x) { long div = n / x; if(div * x != n) { div++; } return div; } private static int ceil(int n, int x) { int div = n / x; if(div * x != n) { div++; } return div; } private static int abs(int x) { if (x < 0) { return -x; } return x; } private static double abs(double x) { if (x < 0) { return -x; } return x; } private static long abs(long x) { if(x < 0) { return -x; } return x; } private static int lcm(int a, int b) { return (a * b) / gcd(a, b); } private static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } private static int log(long x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static long min(long a, long b) { if (a < b) { return a; } return b; } private static int min(int a, int b) { if (a < b) { return a; } return b; } private static long max(long a, long b) { if (a < b) { return b; } return a; } private static int max(int a, int b) { if (a < b) { return b; } return a; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { return null; } return tokenizer.nextToken(); } public String nextLine() { String line = null; try { tokenizer = null; line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public boolean hasNext() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public int[] nextIntArr(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[] nextIntArr1(int n) { int arr[] = new int[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr1(int n) { long arr[] = new long[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextLong(); } return arr; } public void close() { try { if(reader != null) { reader.close(); } } catch(Exception e) { } } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
ef60fd3f32c94709ae011c4041e9e2a3
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer buffer; public static void solve() { int n = ni(); int[]a = new int[2*n]; for (int i=1;i<n;i++) { int ind = i/2 + ((i+1)%2)*(n-1); a[ind] = a[ind+(n-i)] = i; } for (int i=0;i<2*n;i++) { if (a[i]==0) a[i] = n; out.print(a[i] + " "); } } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } static String next() { while (buffer == null || !buffer.hasMoreElements()) { try { buffer = new StringTokenizer(in.readLine()); } catch (IOException e) { } } return buffer.nextToken(); } static int ni() { return Integer.parseInt(next()); } static long nl() { return Long.parseLong(next()); } static double nd() { return Double.parseDouble(next()); } static String ns() { return next(); } static int[] ni(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = Integer.parseInt(next()); return res; } static long[] nl(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = Long.parseLong(next()); return res; } static double[] nd(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) res[i] = Double.parseDouble(next()); return res; } static String[] ns(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = next(); return res; } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
7147ef1ae6cfab813482cbf9eb15af0e
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static final int MAXIMUM_VALUE = (int)1e6; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); InputReader inputReader = new InputReader(in); PrintWriter out = new PrintWriter(System.out); int n = inputReader.getNextInt(); int[] solution = new int[2*n]; int evenOffset = n; int oddOffset = 0; for(int i = 1; i < n; i++) { if(i % 2 == 1) { solution[oddOffset] = i; solution[oddOffset + n - i] = i; oddOffset++; } else { solution[evenOffset] = i; solution[evenOffset + n - i] = i; evenOffset++; } } for(int i = 0; i < solution.length; i++) { if(solution[i] == 0) { solution[i] = n; } out.print(solution[i] + " "); } in.close(); out.close(); } public static class InputReader { static final String SEPARATOR = " "; String[] split; int head = 0; BufferedReader in; public InputReader(BufferedReader in) { this.in = in; } private void fillBuffer() throws IOException { if(split == null || head >= split.length) { head = 0; split = in.readLine().split(SEPARATOR); } } public String getNextToken() throws IOException { fillBuffer(); return split[head++]; } public int getNextInt() throws IOException { return Integer.parseInt(getNextToken()); } public long getNextLong() throws IOException { return Long.parseLong(getNextToken()); } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
8290d899d07d8b2d51363c87b754a2c6
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
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 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; int n = parseInt(in.readLine()); int m = 2*n; int [] a = new int[m]; if(n%2==0) { int j = 1; for(int i=0; i<n/2; i++,j+=2) a[i] = a[n-1-i] = j; j = 2; for(int i=n+1; i<(m+n)/2; i++,j+=2) a[i] = a[m-1-(i-n-1)] = j; a[n] = a[(m+n)/2] = j; } else { int j = 2; for(int i=n; i<n+n/2; i++,j+=2) a[i] = a[m-2-(i-n)] = j; j = 1; for(int i=0; i<n/2; i++,j+=2) a[i] = a[n-1-i] = j; a[n/2] = a[m-1] = j; } out.append(a[0]); for(int i=1; i<m; i++) out.append(" ").append(a[i]); System.out.println(out); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
34cd8a8ef48d29f1cfc862cfa7771704
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; public class Solution123 implements Runnable { static final int MAX = 1000000007; 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 Solution123(),"Solution123",1<<26).start(); } static long[] ans = new long[1000001]; static int[] temp; static long[][] count = new long[1000001][9]; static int[] freq; static HashSet<Integer> pw2 = new HashSet(); static ArrayList<Integer> ar[] = new ArrayList[9]; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = new int[2*n + 1]; int j = 1; for(int i = 1;i <= n;i+=2){ arr[j] = i; arr[j + (n-i)] = i; j++; } j = n + 2; for(int i = 2;i <= n;i+=2){ arr[j] = i; arr[j + (n-i)] = i; j++; } arr[n+1] = n; for(int i = 1;i <= 2*n;i++){ if(arr[i] == 0){ arr[i] = n; } } for(int i = 1;i <= 2*n;i++){ w.print(arr[i] + " "); } w.close(); } static void fun(){ ans[1] = 2; for(int i = 2;i <= ans.length-1;i++){ ans[i] = (ans[i-1] % MAX + ans[i-1] % MAX - (i/2) + ((i % 2 == 0) ? dpe[(i-2)/2]%MAX : dpo[(i-2)/2]%MAX))%MAX; } } static long[] num = new long[1000001]; static long[] dpo = new long[500001]; static long[] dpe = new long[500001]; static void power(){ dpe[0] = 0; for(int i = 1;i < num.length;i++){ num[i] = i-1; if(i == 1){ dpo[0] = (num[i]); }else if(i == 2){ dpe[1] = num[i]; }else if(i % 2 != 0){ dpo[i/2] = dpo[i/2-1] + num[i]; }else{ dpe[i/2] = dpe[i/2-1] + num[i]; } } } static class Pair{ int a; int b; int c; Pair(int a,int b,int c){ this.a = a; this.b = b; this.c = c; } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
24a68d1cf3d41fc4a1e35f7545637ed3
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
/** * * @author meashish */ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; public class Main { InputReader in; Printer out; long MOD = 1000000007; private void start() throws Exception { int n = in.nextInt(); int a1[] = new int[n]; int a2[] = new int[n]; Arrays.fill(a1, -1); Arrays.fill(a2, -1); int l = 1, r = n; for (int i = 1; i < n; i += 2) { a1[l - 1] = i; a1[r - 1] = i; l++; r--; } l = 1; r = n - 1; for (int i = 2; i < n; i += 2) { a2[l - 1] = i; a2[r - 1] = i; l++; r--; } ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(a1[i]); } for (int i = 0; i < n; i++) { list.add(a2[i]); } for (int i = 0; i < 2 * n; i++) { if (list.get(i) == -1) { out.print(n + " "); } else { out.print(list.get(i) + " "); } } out.println(); out.flush(); } long power(long x, long n) { if (n <= 0) { return 1; } long y = power(x, n / 2); if ((n & 1) == 1) { return (((y * y) % MOD) * x) % MOD; } return (y * y) % MOD; } public int gcd(int a, int b) { a = Math.abs(a); b = Math.abs(b); return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue(); } public static void main(String[] args) throws Exception { InputReader in; PrintStream out; //in = new InputReader(new FileInputStream(new File("in.txt"))); //out = new PrintStream("out.txt"); in = new InputReader(System.in); out = System.out; Main main = new Main(); main.in = in; main.out = new Printer(out); main.start(); } private 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 nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class Printer { PrintStream out; StringBuilder buffer = new StringBuilder(); boolean autoFlush; public Printer(PrintStream out) { this.out = out; } public Printer(PrintStream out, boolean autoFlush) { this.out = out; this.autoFlush = autoFlush; } public void println() { buffer.append("\n"); if (autoFlush) { flush(); } } public void println(int n) { println(Integer.toString(n)); } public void println(long n) { println(Long.toString(n)); } public void println(double n) { println(Double.toString(n)); } public void println(float n) { println(Float.toString(n)); } public void println(boolean n) { println(Boolean.toString(n)); } public void println(char n) { println(Character.toString(n)); } public void println(byte n) { println(Byte.toString(n)); } public void println(short n) { println(Short.toString(n)); } public void println(Object o) { println(o.toString()); } public void println(Object[] o) { println(Arrays.deepToString(o)); } public void println(String s) { buffer.append(s).append("\n"); if (autoFlush) { flush(); } } public void print(char s) { buffer.append(s); if (autoFlush) { flush(); } } public void print(String s) { buffer.append(s); if (autoFlush) { flush(); } } public void flush() { try { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(out)); log.write(buffer.toString()); log.flush(); buffer = new StringBuilder(); } catch (Exception e) { e.printStackTrace(); } } } private class Pair<T, U> implements Serializable { int x; int index; int ans = 0; private T key; public T getKey() { return key; } private U value; public U getValue() { return value; } public Pair(T key, U value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (!this.key.equals(other.key)) { return false; } return this.value.equals(other.value); } @Override public int hashCode() { return key.hashCode() + 13 * value.hashCode(); } } private static class Bit { int N; int ft[] = new int[10000000]; Bit(int n) { N = n; } void update(int p, int v) { for (; p <= N; p += p & (-p)) { ft[p] += v; } } void update(int a, int b, int v) { update(a, v); update(b + 1, -v); } long query(int b) { long sum = 0; for (; b > 0; b -= b & (-b)) { sum += ft[b]; } return sum; } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
15f6e06abee7149076d789bc9b71bbc4
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
/** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class eduRnd_7_D { 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[] an=new int[2*n+1]; if(n%2==0){ int t=1; for(int i=1;i<=n-1;i=i+2) { an[t]=an[n-(t-1)]=i;t++; } t=0; // for(int i=1;i<=2*n;i++) // System.out.print(an[i]+ " "); // an[n]=n-1; for(int i=2;i<=n-2;i=i+2) { an[n+2+t]=an[2*n-t]=i;t++; } for(int i=1;i<=2*n;i++) if(an[i]==0)an[i]=n; for(int i=1;i<=2*n;i++) op.append(an[i]+" "); System.out.println(op); return; } else{ int t=1; for(int i=1;i<=n-1;i=i+2) { an[t]=an[n-(t-1)]=i;t++; } t=0; for(int i=2;i<=n-1;i=i+2) { an[n+2+t]=an[2*n-t]=i;t++; } for(int i=1;i<=2*n;i++) if(an[i]==0)an[i]=n; for(int i=1;i<=2*n;i++) op.append(an[i]+" "); System.out.println(op); } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
effa3eacc19048c14edf356aac40893e
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.util.*; public class CF622D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] aa = new int[n + n]; for (int k = 1; k + k <= n; k++) aa[k] = aa[n + 1 - k] = k + k - 1; for (int k = 1; k + k <= n - 1; k++) aa[n + k] = aa[n + n - k] = k + k; aa[0] = n; if (n % 2 == 1) aa[n / 2 + 1] = n; else aa[n + (n - 1) / 2 + 1] = n; StringBuilder sb = new StringBuilder(); for (int k = 0; k < n + n; k++) sb.append(aa[k] + " "); System.out.println(sb); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
39d48efe685a454a9f69e9e1bbe906c4
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.util.*; public class Test { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args)throws Exception { Reader.init(System.in); int n = Reader.nextInt(); StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); if(n == 1) { pw.print("1 1"); pw.close(); return; } else if(n == 2) { pw.print("1 1 2 2"); pw.close(); return; } if(n%2 == 0) { for(int i = 1 ; i<=(n-1) ; i+=2)s1.append(i).append(" "); for(int i = n-1 ; i>=1 ; i-=2)s1.append(i).append(" "); for(int i = 2 ; i<=n ; i+=2)s2.append(i).append(" "); for(int i = n-2 ; i>=2 ; i-=2)s2.append(i).append(" "); } else { for(int i = 2 ; i<=(n-1) ; i+=2)s1.append(i).append(" "); for(int i = n-1 ; i>=2 ; i-=2)s1.append(i).append(" "); for(int i = 1 ; i<=n ; i+=2)s2.append(i).append(" "); for(int i = n-2 ; i>=1 ; i-=2)s2.append(i).append(" "); } pw.print(s1); pw.print(s2); pw.print(n); pw.close(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; public static int pars(String x) { int num = 0; int i = 0; if (x.charAt(0) == '-') { i = 1; } for (; i < x.length(); i++) { num = num * 10 + (x.charAt(i) - '0'); } if (x.charAt(0) == '-') { return -num; } return num; } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static void init(FileReader input) { reader = new BufferedReader(input); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return pars(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
c4a3feb1ce49cd36d5cae9f9fe37b285
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; public class OptimalNumberPermutation { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int numbers = Integer.parseInt(br.readLine()); int answer[] = new int[numbers * 2 + 1]; int oddMarker = 1, evenMarker = 0, divider = numbers + 1, divider2 = numbers * 2 - 1; for(int i = 1; i <= numbers; i++) { if(i % 2 != 0) { answer[oddMarker] = i; if(i == numbers) { answer[numbers * 2] = i; }else{ answer[(divider - oddMarker)] = i; } oddMarker++; }else { answer[divider + evenMarker] = i; if(i == numbers) { answer[numbers * 2] = i; }else{ answer[(divider2 - evenMarker)] = i; } evenMarker++; } } OutputStream os = new BufferedOutputStream(System.out); for(int j = 1; j <= 2 * numbers; j++) { os.write((answer[j]+" ").getBytes()); } os.flush(); br.close(); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
81c1d0c8b04c6dece018b25e8947f30f
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class D { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true); int[] answer = new int[2*n]; Arrays.fill(answer, n); for(int i =0;i<n/2;i++){ out.print(1 + 2*i + " "); } if(n%2==1) out.print(n + " "); for(int i=n/2-1;i>-1;i--){ out.print(1 +2*i + " "); } for(int i =0;i<n/2;i++){ out.print(2 + 2*i + " "); } if(n%2==1 && n>1) out.print(n-1 + " "); for(int i=n/2-1;i>0;i--){ out.print(2*i + " "); } out.print(n); out.close(); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
d959d62a53491655cd59b43d6a4e46cc
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import java.io.*; import java.util.*; public class Main { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); int[] arr = new int[2 * n + 1]; for (int i = 1, p = 1; i < n; i += 2) { if (arr[p] == 0) { arr[p] = i; arr[p + n - i] = i; } else { p++; i -= 2; } } for (int i = 2, p = n + 1; i < n; i += 2) { if (arr[p] == 0) { arr[p] = i; arr[p + n - i] = i; } else { p++; i -= 2; } } for (int i = 1; i <= 2 * n; i++) { if (arr[i] == 0) { arr[i] = n; } out.print(arr[i] + " "); } out.println(); } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new Main().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(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); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
76205de88d4848e283f6a8c4e7a16291
train_002.jsonl
1455116400
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi &lt; yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .
256 megabytes
import static java.lang.Math.*; import java.io.*; import java.util.*; import java.math.*; public class Main { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.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()); } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int[] a = new int[2 * n + 1]; int k = 1; for (int i = 1; i <= n - 1; i += 2) { a[k] = i; a[n - k + 1] = i; k++; } k = 1; for (int i = 2; i <= n - 1; i += 2) { a[n + k] = i; a[2 * n - k] = i; k++; } for (int i = 1; i <= 2 * n; i++) { out.print(a[i] == 0 ? n : a[i]); out.print(" "); } out.close(); } public static void main(String[] args) throws Exception { new Main().run(); } }
Java
["2", "1"]
1 second
["1 1 2 2", "1 1"]
null
Java 8
standard input
[ "constructive algorithms" ]
c234cb0321e2bd235cd539a63364b152
The only line contains integer n (1 ≤ n ≤ 5·105).
1,900
Print 2n integers — the permuted array a that minimizes the value of the sum s.
standard output
PASSED
3aa1d4613edcc234c077d945bc7e8a18
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Kattio in = new Kattio(System.in); int n = in.nextInt(); char[] arr = in.next().toCharArray(); for (int i = 0; i < n; ++i) { char c = arr[i]; } int turns = n - 11; int t1 = 0; int t2 = 0; for (int i = 0; i < turns; ++i) { if (i % 2 == 0) { ++t1; } else { ++t2; } } // System.err.println(t1 + " " + t2); // System.err.println(new String(arr)); for (int i = 0; i < n && t2 > 0; ++i) { if (arr[i] == '8') { arr[i] = 'x'; --t2; } } // System.err.println(new String(arr)); for (int i = 0; i < n && t1 > 0; ++i) { if (arr[i] != '8' && arr[i] != 'x') { arr[i] = 'x'; --t1; } } // System.err.println(new String(arr)); for (int i = n - 1; i >= 0 && t1 > 0; --i) { if (arr[i] != 'x') { arr[i] = 'x'; --t1; } } boolean ans = true; for (int i = 0; i < n; ++i) { if (arr[i] != 'x') { ans = arr[i] == '8'; break; } } // System.err.println(new String(arr)); in.println(ans ? "YES" : "NO"); in.close(); } } class Kattio extends PrintWriter { private BufferedReader r; private String line; private StringTokenizer st; private String token; public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasNext() { return peekToken() != null; } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public String next() { return nextToken(); } public String nextLine() { token = null; st = null; try { return r.readLine(); } catch (IOException e) { return null; } } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } class UnionFind { private Vector<Integer> p, rank, setSize; private int numSets; public UnionFind(int N) { p = new Vector<Integer>(N); rank = new Vector<Integer>(N); setSize = new Vector<Integer>(N); numSets = N; for (int i = 0; i < N; i++) { p.add(i); rank.add(0); setSize.add(1); } } public int findSet(int i) { if (p.get(i) == i) return i; else { int ret = findSet(p.get(i)); p.set(i, ret); return ret; } } public Boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (!isSameSet(i, j)) { numSets--; int x = findSet(i), y = findSet(j); // rank is used to keep the tree short if (rank.get(x) > rank.get(y)) { p.set(y, x); setSize.set(x, setSize.get(x) + setSize.get(y)); } else { p.set(x, y); setSize.set(y, setSize.get(y) + setSize.get(x)); if (rank.get(x) == rank.get(y)) rank.set(y, rank.get(y) + 1); } } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize.get(findSet(i)); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
297e0faf7cd2074bf2cdf9bd6b7a1213
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; public class GameWithTelephoneNumbers { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Scanner scanner = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); String string = br.readLine(); StringBuffer ss = new StringBuffer(string); int l = n - 11; int v1= l/2 , v2 = v1; while(n>11) { boolean flag = false; while(ss.charAt(0) != '8' && v1>0) { flag = true; n--; ss.delete(0, 1); v1--; } while(ss.charAt(0) == '8' && v2>0) { flag = true; n--; ss.delete(0, 1); v2--; } if(!flag) break; } //System.out.println(ss); if(ss.charAt(0) == '8') out.write("YES"); else out.write("NO"); out.flush(); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
3ab7219d139ab079a66ae7dccb5749ba
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
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 Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here FastReader sc=new FastReader(); int n=sc.I(); char[] c=sc.nextLine().toCharArray(); int e=0,l=-1,i=0; int m=(n-11)/2; for(i=0;i<n;i++){ if(c[i]=='8'){ e++; if(e-m==1) break; } } if(i<=2*m&&i>=m&&e-m==1){ System.out.println("YES"); } else System.out.println("NO"); } 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 I() { return Integer.parseInt(next()); } long L() { return Long.parseLong(next()); } double D() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int gcd(int a,int b) { if(a%b==0) return b; return gcd(b,a%b); } static float power(float x, int y) { float temp; if( y == 0) return 1; temp = power(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x * temp * temp; else return (temp * temp) / x; } } static long pow(int a,int b) { long result=1; if(b==0) return 1; long x=a; while(b>0) { if(b%2!=0) result*=x; x=x*x; b=b/2; } return result; } static ArrayList<Integer> sieveOfEratosthenes(int n) { ArrayList<Integer> arr=new ArrayList<Integer>(); boolean prime[] = new boolean[n+1]; for(int i=2;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { arr.add(p); for(int i = p*p; i <= n; i += p) prime[i] = false; } } return arr; } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
4c8ac5f67275d3c5eec50c06e30eda7a
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; public class _1155B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); StringBuilder s = new StringBuilder(sc.next()); int eight = 0; for (int i = 0; i < n-10 ; i++) { if (s.charAt(i) == '8') eight++; } if (eight >(n-11)/2 ) { System.out.println("YES"); } else { System.out.println("NO"); } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
a872168cc90870e4050a1cedabb4636a
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; import java.io.*; public class TeleGame{ public static void main(String arg[]) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int sum=0, j, i, t, n; n=Integer.parseInt(br.readLine()); String str = br.readLine(); String s="",c=""; int ch=(n-11)/2; for(i=0 ; i<n-10 ; i++) if(str.charAt(i)=='8') sum++; //System.out.println(str); //System.out.println(str+" "+n); if(ch<sum) System.out.print("Yes"); else System.out.print("NO"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
d7a46cc93ec500d987cd277b896e8dcd
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BGameWithTelephoneNumbers solver = new BGameWithTelephoneNumbers(); solver.solve(1, in, out); out.close(); } static class BGameWithTelephoneNumbers { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); String s = in.scanString(); int c = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '8') { c++; } } if (c == 0) { out.println("NO"); } else { if ((n - 11) / 2 >= c) { out.println("NO"); } else { int round = (n - 11) / 2; c = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '8') { c++; if (round + 1 <= c) { if (n - i >= 11) { out.println("YES"); return; } } } } out.println("NO"); } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
f0f983181997f2e7cb5ef39c3da3110b
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.*; import java.util.*; public class EduA { public static void main(String[] args) { FastScanner s = new FastScanner(); int n = s.nextInt(), c=0; char[] arr = s.nextString().toCharArray(); int x = n - 11 , index = -1; x=x/2; boolean[] mark = new boolean[n]; for(int i = 0;i < n ;i++) { if(arr[i]=='8')c++; if(arr[i]=='8'&&x>0) { mark[i] = true; x--; } } if(x>0) { for(int i = n-1;i>=0 ;i--) { if(!mark[i]&&x>0) { mark[i] = true; x--; } } } int y = (n-11)/2; for(int i = 0; i<n; i++) { if(y>0 &&!mark[i]) { if(arr[i]!='8'&&y>0) { mark[i] = true;y--;} } } if(y>0) { for(int i = n-1;i>=0 ;i--) { if(!mark[i]&&y>0) { mark[i] = true; y--; } } } int f = -1; for(int i = 0;i<n;i++) { //System.out.print(mark[i]+" "); if(f==-1&&!mark[i]) { f = i; } } //System.out.println(f); //if() if(arr[f]=='8') System.out.println("YES"); else System.out.println("NO"); } static class FastScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner() { this(System.in); } public FastScanner(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
341c24701007389e31a74c5d3ef4c278
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.*; import java.util.Scanner; public class Main{ public static void main(String[] args) throws IOException{ Scanner reader = new Scanner(System.in); int n = reader.nextInt(); StringBuilder stringBuilder = new StringBuilder(reader.next()); int turns = (n - 11) / 2; int count = turns; int index = 0; while(count > 0 && index < stringBuilder.length()){ if(stringBuilder.charAt(index) == '8'){ stringBuilder.deleteCharAt(index); --count; }else ++index; } count = turns; index = 0; while(count > 0 && index < stringBuilder.length()){ if(stringBuilder.charAt(index) != '8'){ stringBuilder.deleteCharAt(index); --count; }else ++index; } if(stringBuilder.charAt(0) == '8') System.out.println("YES"); else System.out.println("NO"); } } class Reader{ final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() throws IOException{ din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
d7eeb32129813fcdd6b2262aabfbbb58
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.*; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int n=sc.nextInt(); String h=sc.nextLine(); boolean can=false; //int num8=0; TreeSet<Integer> ts=new TreeSet<>(); for(int i=0;i<n;i++) if(h.charAt(i)=='8') { // num8++; ts.add(i); } int del=n-11; //if(del/2>num8) { //System.out.println("NO"); //return; //} // System.out.println(ts); int vas=del/2; while(vas!=0) { vas--; if(ts.isEmpty()) { System.out.println("NO"); return; } ts.remove(ts.first()); } if(ts.isEmpty()) { System.out.println("NO"); return; } int c=ts.first(); if(c<=del) can=true; //System.out.println(c); if(can) out.println("YES"); else out.println("NO"); out.flush(); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static class pair{ int num; int idx; pair(int n,int i){ num=n; idx=i; } public String toString(){ return num+" "+idx; } } static class unionfind { int[] p; int[] size; unionfind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } Arrays.fill(size, 1); } int findSet(int v) { if (v == p[v]) return v; return p[v] = findSet(p[v]); } boolean sameSet(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; return false; } int max() { int max = 0; for (int i = 0; i < size.length; i++) if (size[i] > max) max = size[i]; return max; } void combine(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return; if (size[a] > size[b]) { p[b] = a; size[a] += size[b]; } else { p[a] = b; size[b] += size[a]; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
22bbd9fdbed3960f23708d35b511c1d0
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numCount = in.nextInt(); in.nextLine(); String number = in.nextLine(); int cycleCount = (numCount - 11) / 2; int count8 = (int) number.chars() .filter(c -> (char) c == '8') .count(); if (cycleCount >= count8) { System.out.println("NO"); return; } int countBetween8 = 0; int n8, lastn8 = 0; for (int i = 0; i < cycleCount + 1; i++) { n8 = number.indexOf('8', lastn8); countBetween8 += n8 - lastn8; lastn8 = n8 + 1; } System.out.println(countBetween8 > cycleCount ? "NO" : "YES"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
817250579bd3b45b2a63d0d801c87d11
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; N=Integer.parseInt(br.readLine().trim()); char str[]=br.readLine().trim().toCharArray(); int P=(N-11)/2; int V=N-11-P; for(i=0;i<N;i++) { if(str[i]=='8'&&P>0) { str[i]='a'; P--; } else if(str[i]!='8'&&V>0) { str[i]='a'; V--; } } for(i=0;i<N;i++) if(str[i]!='a') break; if(str[i]=='8') System.out.println("YES"); else System.out.println("NO"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
baa5edbd8e3b4ed46b279abf660d1c81
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; N=Integer.parseInt(br.readLine().trim()); char str[]=br.readLine().trim().toCharArray(); int P=(N-11)/2; int V=N-11-P; int c=0; for(i=0;i<N;i++) if(str[i]=='8') c++; int left=c-P; if(left<=0) { System.out.println("NO"); System.exit(0); } int left2=0; for(i=0;i<N;i++) { if(str[i]!='8') left2++; else { P--; if(P==-1) break; } } left2-=V; if(left2>0) System.out.println("NO"); else System.out.println("YES"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
4730af327c8a1addf81907a93d167452
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.Scanner; public final class GameWithTelePhoneCF { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String s=sc.next(); int count=0,last=0; int diff=s.length()-11; int kth=0; for(int i=0;i<n;i++){ if(s.charAt(i)=='8'){ count++; if(count==(diff/2+1)){ kth=i; } } } if(count>diff/2){ if( kth<=diff){ System.out.println("YES"); }else{ System.out.println("NO"); } }else{ System.out.println("NO"); } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
a7875276a9d9f27ac93fd64eac4627a8
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import javax.print.DocFlavor; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.nio.Buffer; import java.sql.BatchUpdateException; import java.util.*; import java.util.stream.Stream; import java.util.Vector; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.Math.*; import java.util.*; import java.nio.file.StandardOpenOption; import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Iterator; import java.util.PriorityQueue; public class icpc { public static void main(String[] args)throws IOException { // Reader in = new Reader(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String s = in.readLine(); ArrayList<Integer> indices = new ArrayList<>(); for(int i=0;i<s.length();i++) { int x = s.charAt(i) - '0'; if(x == 8) indices.add(i); } int moves = n - 11; int movesForPetya = moves / 2; int movesForVasya = moves / 2; if(movesForPetya >= indices.size()) System.out.println("NO"); else { int lastindex = indices.get(movesForPetya); if((movesForVasya + movesForPetya) >= lastindex) System.out.println("YES"); else System.out.println("NO"); } } } class Game implements Comparable<Game> { long x; int y; Game(long a,int b) { this.x = a; this.y = b; } public int compareTo(Game ob) { if(this.x < ob.x) return 1; else if(this.x > ob.x) return -1; return 0; } } class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long 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 */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second 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() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { String a; String b; Node(String s1,String s2) { this.a = s1; this.b = s2; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.a.equals(obj.a) && this.b.equals(obj.b)) return true; return false; } @Override public int hashCode() { return (int)this.a.length(); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree1 { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MAX_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.min(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int[] segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len - 1,qlow,qhigh,0); } private int rangeMinimumQuery(int[] segmentTree,int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high) { return segmentTree[pos]; } else if(qlow > high || qhigh < low) { return Integer.MAX_VALUE; } int mid = (low + high)/2; return Math.min(rangeMinimumQuery(segmentTree,low,mid,qlow,qhigh,2*pos+1),rangeMinimumQuery(segmentTree,mid+1,high,qlow,qhigh,2*pos+2)); } public void updateSegmentTreeRangeLazy(int[] input,int[] segmentTree,int[] lazy,int startRange,int endRange,int delta) { updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,0,input.length-1,0); } private void updateSegmentTreeRangeLazy(int[] input,int[] segmentTree,int[] lazy,int startRange,int endRange,int delta,int low,int high,int pos) { if(low > high) { return; } if(lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if(low != high) { lazy[2*pos+1] += lazy[pos]; lazy[2*pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(startRange > high || endRange < low) return; if(startRange <= low && endRange >= high) { segmentTree[pos] += delta; if(low != high) { lazy[2*pos + 1] += delta; lazy[2*pos + 2] += delta; } return; } int mid = (low + high)/2; updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,low,mid,2*pos + 1); updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,mid + 1,high,2 * pos + 2); segmentTree[pos] += Math.min(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQueryLazy(int[] segmentTree,int[] lazy,int qlow,int qhigh,int len) { return rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,0,len - 1,0); } private int rangeMinimumQueryLazy(int[] segmentTree,int[] lazy,int qlow,int qhigh,int low,int high,int pos) { if(low > high) return Integer.MAX_VALUE; if(lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if(low != high) { lazy[2*pos + 1] += lazy[pos]; lazy[2*pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(qlow > high || qhigh < low) return Integer.MAX_VALUE; if(qlow <= low && qhigh >= low) return segmentTree[pos]; int mid = (low + high)/2; return Math.min(rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,low,mid,2*pos + 1),rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,mid + 1,high,2*pos + 2)); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
663529f89891ef5662e18797be29ce7b
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.management.MemoryType; import java.math.BigInteger; import java.util.*; public class Main { static final int INF = Integer.MAX_VALUE; static int mergeSort(int[] a,int [] c, int begin, int end) { int inversion=0; if(begin < end) { inversion=0; int mid = (begin + end) >>1; inversion+= mergeSort(a,c, begin, mid); inversion+=mergeSort(a, c,mid + 1, end); inversion+=merge(a,c, begin, mid, end); } return inversion; } static int merge(int[] a,int[]c, int b, int mid, int e) { int n1 = mid - b + 1; int n2 = e - mid; int[] L = new int[n1+1], R = new int[n2+1]; int[] L1 = new int[n1+1], R1 = new int[n2+1]; //inversion int inversion=0; for(int i = 0; i < n1; i++) { L[i] = a[b + i]; L1[i] = c[b + i]; } for(int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; R1[i] = c[mid + 1 + i]; } L[n1] = R[n2] = INF; for(int k = b, i = 0, j = 0; k <= e; k++) if(L[i] <= R[j]){ a[k] = L[i]; c[k] = L1[i++]; } else { a[k] = R[j]; c[k] = R1[j++]; inversion=inversion+(n1-i); } return inversion; } public static void main (String[]args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { int n = in.nextInt(); char[] a=in.next().toCharArray(); int [] f= new int[10]; PriorityQueue<Integer>map= new PriorityQueue<>(); for (int i = 0; i < n; i++) if (a[i]=='8')map.add(i); int rem=n-11; rem/=2; while (rem-->0&&!map.isEmpty())a[map.poll()]='.'; if (map.isEmpty())or.println("NO"); else{ int g=map.poll(); rem=n-11; if (rem%2==1)rem=(rem+1)/2; else rem/=2; for (int i = 0; rem>0&&i <n; i++) { if (i!=g&&a[i]!='.'){ a[i]='.'; --rem; } } for (int i = 0; i < n; i++) { if (a[i]!='.'){ if (a[i]=='8') { or.println("YES"); return; }else break; } } or.println("NO"); } } } 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(); } } } class Triple{ int first,second,third; public Triple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
1a6659f13a065f7ac100c296f98bfd8e
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.StringTokenizer; public class GameWithTelephoneNumbers implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int n = in.ni(); char[] x = in.next().toCharArray(); ArrayDeque<Integer> eights = new ArrayDeque<>(); ArrayDeque<Integer> others = new ArrayDeque<>(); for (int i = 0; i < n; i++) { if (x[i] == '8') { eights.addLast(i); } else { others.addLast(i); } } boolean vasya = true, possible = true; int digits = n; while (digits > 11) { if (vasya) { if (others.size() > 0) { others.pollFirst(); } else { eights.pollLast(); } } else { if (eights.size() > 0) { eights.pollFirst(); } else { possible = false; break; } } vasya = !vasya; digits--; } possible &= eights.size() > 0 && eights.peekFirst() <= n - 11; out.println(possible ? "YES" : "NO"); } @Override public void close() throws IOException { in.close(); out.close(); } 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 ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (GameWithTelephoneNumbers instance = new GameWithTelephoneNumbers()) { instance.solve(); } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
7709c09c2201c5f1107b7e0fcda2755c
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class TelephoneGame { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; String s; /*int t; t = sc.nextInt(); while(t > 0) {*/ n = sc.nextInt(); s = sc.next(); char str[] = new char[n]; str = s.toCharArray(); ArrayList occurEight = new ArrayList<Integer>(); for(int i = 0; i < s.length(); i++) { if(str[i] == '8') occurEight.add(i); } /*for(int i = 0 ; i < occurEight.size(); i++) { System.out.print(occurEight.get(i) + " "); }*/ int remainMoves = n - 11; boolean NoEightsLeft = false; for(int i = 0 ; i < n; i++) { if(str[i] != '8' && str[i] != '?') //Non 8 characters { str[i] = '?'; //System.out.println("Move made by N - Made Non 8 character as ?"); } else if(str[i] == '?'){ // for question Mark while(i < n) { if(str[i] == '?' || str[i] == '8') i++; else break; } if(i == n) { if(occurEight.size() != 0) { str[(Integer)occurEight.get(occurEight.size() - 1)] = '?'; occurEight.remove(occurEight.size() - 1); } else { NoEightsLeft = true; break; } } else str[i] = '?'; } else if(str[i] == '8'){ //for 8 while(i < n) { if(str[i] == '8' || str[i] == '?') i++; else break; } if(i == n) { if(occurEight.size() != 0) { str[(Integer)occurEight.get(occurEight.size() - 1)] = '?'; occurEight.remove(occurEight.size() - 1); } else { NoEightsLeft = true; break; } } else { str[i] = '?'; } } //P's Move if(occurEight.size() != 0) { str[(Integer)occurEight.get(0)] = '?'; occurEight.remove(0); } else { NoEightsLeft = true; break; } remainMoves -= 2; if(remainMoves == 0) break; } /*for(int i = 0; i < n; i++) { System.out.println("str[" + i + "]=" + str[i] + " "); }*/ if(NoEightsLeft) { System.out.println("NO"); } else { if(occurEight.size()!= 0) { for(int i = 0; i < (Integer)occurEight.get(0); i++) { if(str[i] != '?') { System.out.println("NO"); return; } } System.out.println("YES"); } else { System.out.println("NO"); } } /*t--; } */ } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
b0e6c3e0145fe55aaefb77d21f1548d4
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.*; import java.util.*; public class Cony { static long mat[][] ; static int lastocc[] ; public static void main(String[] args) throws IOException { BufferedReader jk = new BufferedReader(new InputStreamReader(System.in)) ; PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)) ; StringTokenizer ana = new StringTokenizer(jk.readLine()) ; int n = Integer.parseInt(ana.nextToken()) ; String s = jk.readLine() ; boolean tem = false ; int k = (n-11)/2 ; int j = -1 ; for(int i=0 ; i< n ;i++) { if(!tem) { if(s.charAt(i)=='8') { k-- ; if(k==0) tem = true ; } } else { if(s.charAt(i)=='8') { j= i ; break ; } } } if(j==-1) { System.out.println("NO"); } else { if(n-j>=11) System.out.println("YES"); else System.out.println("NO"); } out.flush(); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
99918e0a7355efcf3804a0d0b2a72f63
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
/** * @author cplayer on 2018/6/23. * @version 1.0 */ import java.util.*; import java.util.stream.IntStream; import java.io.*; import java.lang.*; import java.math.BigInteger; public class Main { public static void main(String[] args) { try { InputReader in; PrintWriter out; boolean useOutput = false; if (System.getProperty("ONLINE_JUDGE") == null) useOutput = true; if (useOutput) { FileInputStream fin = new FileInputStream(new File("src/data.in")); in = new InputReader(fin); FileOutputStream fout = new FileOutputStream(new File("src/data.out")); out = new PrintWriter(fout); } else { InputStream inputStream = System.in; in = new InputReader(inputStream); OutputStream outputStream = System.out; out = new PrintWriter(outputStream); } Solver solver = new Solver(in, out); solver.solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } static class Solver { private InputReader cin; private PrintWriter cout; Solver (InputReader cin, PrintWriter cout) { this.cin = cin; this.cout = cout; } public void solve () { try { int n = cin.nextInt(); char str[] = cin.next().toCharArray(); int cnt8 = 0, t = (n - 11) / 2; for (int i = 0; i + 11 < n; ++i) { if (str[i] == '8') cnt8++; } if (cnt8 > t) { cout.println("YES"); } else if (cnt8 == t) { if (str[n - 11] == '8') cout.println("YES"); else cout.println("NO"); } else { cout.println("NO"); } } catch (RuntimeException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1000000); 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
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
d1f5bd9fcaee926805c59210aae89cf0
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /** * Author : joney_000[developer.jaswant@gmail.com] * Algorithm : Extended Euclid Algo: find 3 things X, Y, GCD(A, B) Such that X * A + Y * B = GCD(A, B) * Time : O(MAX(A, B)) Space : O(MAX(A, B)) * Platform : Codeforces * Ref : https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/tutorial/ */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } void run()throws Exception{ // int tests = i(); // for(int t = 1; t <= tests; t++){ int n = i(); String s = s(); int cnt[] = new int[10]; LinkedList<Integer> ll [] = new LinkedList[10]; for(int i = 0; i < 10; i++)ll[i] = new LinkedList<Integer>(); for(int i = 1; i <= n; i++){ cnt[s.charAt(i - 1) - '0']++; ll[s.charAt(i - 1) - '0'].addLast(i); } int turn = 0; int tot = n; while(cnt[8] >= 1 && tot > 11){ if(turn == 0){ if(tot == cnt[8]){ cnt[8]--; ll[8].removeLast(); }else{ int min = 2 * n; int mini = 0; for(int i = 0; i < 10; i++){ if(i == 8)continue; if(ll[i].size()==0)continue; if(ll[i].getFirst() < min){ min = ll[i].getFirst(); mini = i; } } ll[mini].removeFirst(); } }else{ if(cnt[8] >= 1){ cnt[8]--; ll[8].removeFirst(); }else{ int max = 0; int maxi = 0; for(int i = 0; i < 10; i++){ if(i == 8)continue; if(ll[i].size()==0)continue; if(ll[i].getLast() > max){ max = ll[i].getLast(); maxi = i; } } ll[maxi].removeLast(); } } turn ^= 1; tot -= 1; } boolean isValid = false; int min = 2 * n; for(int i = 0; i < 10; i++){ if(ll[i].size()==0)continue; min = Math.min(min, ll[i].getFirst()); } if(cnt[8] > 0 && min == ll[8].getFirst()){ out.write("YES"); }else{ out.write("NO"); } // } } void clear(){ } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = mulMod(ans, ans, mod); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = mulMod(a, ans, mod); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private 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 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 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==','){ c = read(); } 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 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 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; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } 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 isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public Pair(){ this.a = 0; this.b = 0; } public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Pair p){ if(this.a == p.a){ return this.b - p.b; } return this.a - p.a; } @Override public String toString(){ return "a = " + this.a + " b = " + this.b; } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
d7951807f409a841f2c3d829533980d7
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; import javax.xml.ws.AsyncHandler; import java.io.*; public class codeforces { public static long GCD(long a, long b) { return b == 0 ? a : GCD(b, a % b); } public static long C(int a, int b, long[][] s) { int m = (int) 1e9 + 7; if (s[a][b] >= 0) { return s[a][b]; } else if (a < b | a < 0 | b < 0) { s[a][b] = 0; return 0; } else if (a == b | b == 0) { s[a][b] = 1; return 1; } else { return s[a][b] = (C(a - 1, b, s) % m + C(a - 1, b - 1, s) % m) % m; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); String s=sc.next(); int a=(n-11)/2; int b=a; int i; boolean t=false; for(i=0;i<(n);i++) { if (a>0) { if(s.charAt(i)=='8' && b>0) { b-=1; } else if(s.charAt(i)=='8') { t=true; break; } else { a-=1; } } else if(b>0) { if(s.charAt(i)=='8' && b>0) { b-=1; } else if(s.charAt(i)=='8') { t=true; break; } else { break; } } else { if( s.charAt(i)=='8') { t=true; } break; } } System.out.println(t?"YES":"NO"); pw.flush(); pw.close(); } 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 { 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
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
f84e10ade3ebe6187f9e2064265a36eb
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProbB { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int length = sc.nextInt(); String str = sc.next(); int counts =0; Set<Integer> st = new HashSet<Integer>(); for(int i=0;i<=length-11;i++) { if(str.charAt(i)=='8') { counts++; //st.add(i); } } if(counts<=(length-11)/2) { System.out.println("NO"); System.exit(0); } System.out.println("YES"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
e17676d2410d503a88e6d3e554a4fc4a
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); int n=sc.nextInt();String s=sc.next(); int count=0; for(int i=0;i<n;i++)if(s.charAt(i)=='8')count++; int pmoves=(n-11)/2; if(count>pmoves){ boolean flag=false; int index=0; int first8=-1; do{ if(s.charAt(index)=='8'){ if(pmoves==0){ first8=index; } pmoves--; } index++; }while(pmoves>=0); if((first8)<=(n-11)) { // System.out.println(first8); System.out.println("YES"); return; } else{ System.out.println("NO");return; } } else System.out.println("NO"); } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
f969b710c56366768ae7d0a03ef6d8fa
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class B { public static void main(String[] args) throws Exception { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); char[] line = scanner.nextLine().toCharArray(); int count = 0; for (int i = 0; i < n - 10; i++) { if (line[i] == '8') count++; } if ((n - 11) / 2 < count) { System.out.println("YES"); } else System.out.println("NO"); } private static class FastScanner { private BufferedReader br; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws IOException { return Integer.parseInt(br.readLine()); } public String nextLine() throws IOException { return br.readLine(); } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
f182a626aaf95f5f3b5deadf5a0872ba
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.util.*; public class CodeForces1155B{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); String s = input.next(); int count = 0; int index = -1; ArrayList<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++){ if(s.charAt(i) == '8'){ arr.add(i); count++; } } int c = (n-11)/2; if(count <= c){ System.out.println("NO"); } else{ //System.out.println(arr.get(c)); if(arr.get(c)-c > c){ System.out.println("NO"); } else{ System.out.println("YES"); } } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
d687a685bdfa071d07b89c9e8beff6b5
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class EducationalRound63A { public static void main(String[] args) { // TODO Auto-generated method stub out=new PrintWriter (new BufferedOutputStream(System.out)); FastReader s=new FastReader(); int n=s.nextInt(); String str=s.next(); int[] arr=new int[n]; int turns=n-11; ArrayList<Integer> eights=new ArrayList<Integer>(); for(int i=0;i<n;i++) { arr[i]=(int)str.charAt(i)-'0'; if(arr[i]==8)eights.add(i); } int eight=0; int pos=0; for(int i=n;i>11;i-=2) { while( pos<n &&(arr[pos]==-1||arr[pos]==8) ) { pos++; } if(pos>=n) { }else { arr[pos]=-1; pos++; } if(eight>=eights.size()) { continue; }else { int current=eights.get(eight); arr[current]=-1; eight++; } } pos=0; while(arr[pos]==-1) { pos++; } if(arr[pos]==8) { out.println("YES"); }else { out.println("NO"); } out.close(); } public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
7eca25284a6e7a48550f0830a501879e
train_002.jsonl
1555943700
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Prac { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[] ) throws Exception { FastReader ip=new FastReader(); int n=ip.nextInt(); String s=ip.nextLine(); int c=0; for(int i=0;i<n;i++) { if(s.charAt(i)=='8') { c++; } } if(c<((n-11)/2)+1) { System.out.println("NO"); }else { int j=0; int a=((n-11))+1; int c1=0; int c2=0; while(a>0) { if(s.charAt(j)!='8') { c2++; }else { c1++; } j++; a--; } if(c1>c2) { System.out.println("YES"); }else { System.out.println("NO"); } } } }
Java
["13\n8380011223344", "15\n807345619350641"]
1 second
["YES", "NO"]
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Java 8
standard input
[ "implementation", "greedy", "games" ]
99f37936b243907bf4ac1822dc547a61
The first line contains one integer $$$n$$$ ($$$13 \le n &lt; 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
1,200
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
standard output
PASSED
a279583b703cbaf4b77e606cfe876946
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.*; import java.util.*; public class Contest201C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("201C.in")); int n = Integer.parseInt(in.readLine()); StringTokenizer st = new StringTokenizer(in.readLine()); int[] seq = new int[n]; for (int i = 0; i < n; i++) seq[i] = Integer.parseInt(st.nextToken()); int g = cgcd(seq); for (int i = 0; i < n; i++) seq[i] /= g; Arrays.sort(seq); int e = seq[n-1] - n; if (e%2==0) System.out.println("Bob"); else System.out.println("Alice"); } static int cgcd(int[] seq) { if (seq.length == 1) return 1; int gcd = gcd(seq[0], seq[1]); for (int i = 2; i < seq.length; i++) { gcd = gcd(gcd, seq[i]); } return gcd; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
4802c78b252063a3986c76857658eba6
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.*; import java.io.*; public class a { static long mod = 1000000007; public static void main(String[] args) throws IOException { // Scanner input = new Scanner(new File("input.txt")); // PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); int n = input.nextInt(); int[] data = new int[n]; for(int i = 0; i<n; i++) data[i] = input.nextInt(); long gcd = data[0]; long max = data[0]; for(int i = 1; i<n; i++) { max = Math.max(max, data[i]); gcd = gcd(gcd, data[i]); } long size = max/gcd; long turns = size - n; System.out.println(turns%2 == 0 ? "Bob" : "Alice"); out.close(); } static long pow(long x, long p) { if (p == 0) return 1; if ((p & 1) > 0) { return (x * pow(x, p - 1)) % mod; } long sqrt = pow(x, p / 2); return (sqrt * sqrt) % mod; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class input { 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static String nextLine() throws IOException { return reader.readLine(); } } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
13221377fa7a3fff01f7f0bf3d7ad4e7
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author coderbd */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.readInt(); Arrays.sort(a); int gcd = Math.GCD(a[0], a[1]); for (int i = 2; i < n; i++) gcd = Math.GCD(gcd, a[i]); out.printLine((a[n-1] / gcd - n) % 2 == 1 ? "Alice" : "Bob"); } } 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 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Math { private Math() {} public static int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
495ac2531dbf791afa5e3d832ee7463d
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } final int MAX = 1000 * 1000; private void solve() throws IOException { int n = nextInt(); int a[] = new int[MAX]; long g = 0; for (int i = 0; i < n; i++) { a[i] = nextInt(); g = gcd(a[i], g); } long max = 0; for (int i = 0; i < n; i++) { max = max(max, a[i] / g); } long ans = max - n; if ((ans % 2) == 1) out.println("Alice"); else out.println("Bob"); } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
6aad472e83208b6f2bf4f8875db96f2c
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; /** * <b> Algorithm on Codeforces. Problem C div 2 </b> </br> * d is GCD(x1, x2, ...., xn) * because we put (xi - xj) into set. So at the end, the set will be : * d 2d 3d ... max(xi) / d . * count even / odd to determine player win * @author Huynh Quang Thao * */ public class Main { public static void main(String[] args) throws Exception { Main main = new Main(); main.run(); } public void run() throws Exception { Scanner sc = null; PrintWriter pr = null; pr=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); // sc = new Scanner(new File("input.txt")); int n = sc.nextInt(); // gcd : GCD(x1, x2, x3, ..., xn) int gcd = 0; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int a = sc.nextInt(); gcd = GCD(a, gcd); max = Math.max(a, max); } int numOfPlay = max / gcd - n; if (numOfPlay % 2 == 0) System.out.println("Bob"); else System.out.println("Alice"); pr.close(); sc.close(); } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } static class Pair { int left, right; public Pair(int left, int right) { this.left = left; this.right = right; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } public long nextLong() { return Long.parseLong(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
3d7c075d43135df86cf1483311231cf1
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import static java.lang.Math.*; import java.util.ArrayList; import java.util.StringTokenizer; /** * * @author pttrung */ public class C { public static long Mod = 1000000007; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int []data = new int[n]; int max = 0; for(int i = 0; i < n; i++){ data[i] = in.nextInt(); max = max > data[i]? max : data[i]; } int d = gcd(data[0] , data[1]); for(int i =2 ; i < n; i++){ d = gcd(d, data[i]); } //System.out.println(d); int val = max / d - n; if(val % 2 == 0){ out.println("Bob"); }else{ out.println("Alice"); } out.close(); } public static long pow(int a, int b) { if (b == 0) { return 1; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % Mod; } else { return a * val * val % Mod; } } public static int gcd(int a , int b){ if(b == 0){ return a; } return gcd(b, a%b); } static void check(Point a, Point b, ArrayList<Point> p, Point[] rec, int index) { for (int i = 0; i < 4; i++) { int m = (i + index) % 4; int j = (i + 1 + index) % 4; Point k = intersect(minus(b, a), minus(rec[m], rec[j]), minus(rec[m], a)); if (k.x >= 0 && k.x <= 1 && k.y >= 0 && k.y <= 1) { Point val = new Point(k.x * minus(b, a).x, k.x * minus(b, a).y); p.add(add(val, a)); // System.out.println(a + " " + b + " " + rec[i] + " " + rec[j]); // System.out.println(add(val, a)); } } } static Point intersect(Point a, Point b, Point c) { double D = cross(a, b); if (D != 0) { return new Point(cross(c, b) / D, cross(a, c) / D); } return null; } static Point convert(Point a, double angle) { double x = a.x * cos(angle) - a.y * sin(angle); double y = a.x * sin(angle) + a.y * cos(angle); return new Point(x, y); } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } static Point add(Point a, Point b) { return new Point(a.x + b.x, a.y + b.y); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } static class Point { double x, y; Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return "Point: " + x + " " + y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
761c30029f59ab500150bb7396a8421c
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main(String []args){ Solution ob = new Solution(); ob.go(); } void pr(String s) { System.out.print(s); } void go(){ Scanner sc=new Scanner (System.in); int n=sc.nextInt(); int x;// = new int[n]; int max=0; boolean odd=false; int gcd=0; for(int i=0;i<n;i++) { x=sc.nextInt(); if (x>max) max=x; if (!odd && x%2==1)odd=true; gcd=gcd|x; } int op; int t; if (odd) op=max-n; else { t=gcd & ~(gcd&(gcd-1)); op=max/t-n; } op=op%2; if (op==0) pr("Bob"); else pr("Alice"); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
1cbb458f978be6d94feff10b0d5bd508
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class TC1 { static int N; static int[] arr; static int MAX=-1; private static int gcd( int a, int b ) // a >= b { if( a<b ) { return gcd( b, a ); } if( b == 0 ) return a; return gcd( b, a%b ); } static int findGCD() { int GCD=arr[0]; for( int i=1; i<N; i++ ) { GCD=gcd( arr[i], GCD ); } return GCD; } static boolean isAlice() { int GCD=findGCD(); if( GCD==1 ) // atleast one pair of co-primes exists { int values=MAX; int moves=values-N; if( moves%2 ==1 ) return true; return false; } int values=MAX/GCD; int moves=values-N; if( moves%2 ==1 ) return true; return false; } public static void main( String[] args ) throws IOException { BufferedReader br=new BufferedReader( new InputStreamReader( System.in )); N=Integer.parseInt(br.readLine() ); String s=br.readLine(); StringTokenizer tok=new StringTokenizer(s); arr=new int[N]; for( int i=0; i<N; i++ ) { arr[i]=Integer.parseInt( tok.nextToken() ); MAX=Math.max(MAX, arr[i]); } if( isAlice() ) System.out.println("Alice"); else System.out.println("Bob"); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
26c5e470bf969610853e597d262f4392
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { Solution sol = new Solution(); System.out.println(sol.solution()); } } class Solution{ private int gcd(int a, int b){ if(a < b)return gcd(b,a); if(b == 0)return a; return gcd(b,a%b); } public String solution() throws NumberFormatException, IOException{ BufferedReader r = new BufferedReader( new InputStreamReader(System.in)); int N = Integer.parseInt(r.readLine()); String[] sarr = r.readLine().split(" "); int[] arr = new int[N]; for(int i = 0; i < N; i++){ int val = Integer.parseInt(sarr[i]); arr[i] = val; } Arrays.sort(arr); int GCD = arr[0]; for(int i = 1; i < N; i++ ){ GCD = gcd(arr[i],GCD); } //System.out.println(arr[N-1] + " " + GCD); return ( arr[N-1]/GCD - N) %2 == 1 ? "Alice" : "Bob"; } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
836130ed2b4c72691ffe50265619e1d4
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.lang.*; public class A { public static void main(String[] args) { A a = new A(); a.run(); } int MAX = 999999999; Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); void quickSort(int[] mas, int l, int r){ int i = l; int j = r; int m = mas[(i + j) / 2]; while (i < j){ while (mas[i] < m) i++; while (m < mas[j]) j--; if (i <= j){ int a = mas[i]; mas[i] = mas[j]; mas[j] = a; i++; j--; } } if (l < j) quickSort(mas, l, j); if (i < r) quickSort(mas, i, r); } int gcd (int a, int b) { if (b == 0) return a; else return gcd (b, a % b); } void run(){ int[] mas = new int[101]; int n = sc.nextInt(); for (int i = 1; i <= n; i++) mas[i] = sc.nextInt(); quickSort(mas, 1, n); int r = MAX; mas[0] = 0; r = mas[1]; for (int i = 2; i <= n; i++){ r = gcd(r,mas[i]); } int k = mas[n]/r - n; if (k%2 == 0) out.println("Bob"); else out.println("Alice"); out.flush(); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
9b990f3251f4e9b5dd8cc6628a47d2b0
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.io.*; import java.util.*; public class third { static long fast_power(long a,long n,long m) { if(n==1) { return a%m; } if(n%2==1) { long power = fast_power(a,(n-1)/2,m)%m; return ((a%m) * ((power*power)%m))%m; } long power = fast_power(a,n/2,m)%m; return (power*power)%m; } static int gcd(int a, int b) { while (b > 0) { int temp = b; b = a % b; // % is remainder a = temp; } return a; } public static void main(String arr[]) { Scanner sc= new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; int gcd1 =-1; int max=0; for(int i =0;i<n;i++) { a[i]= sc.nextInt(); if(gcd1==-1)gcd1=a[i]; else { gcd1 = gcd(gcd1,a[i]); } if(a[i]>max)max=a[i]; } int k = max/gcd1 - n; if(k%2==0) { System.out.println("Bob"); return; } System.out.println("Alice"); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
c19a404f41ff66573abbc9307eabe36b
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.Scanner; /** * User: chen */ public class AliceAndBob { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] num = new int[n]; int maxNum = 0; for (int i = 0; i < n; i++) { num[i] = in.nextInt(); if (num[i] > maxNum) { maxNum = num[i]; } } int minStep = num[0]; for (int i = 1; i < n; i++) { minStep = gcd(num[i], minStep); } final int finalSize = maxNum / minStep; System.out.println((finalSize - n) % 2 == 0 ? "Bob" : "Alice"); } private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
c3659714cdb6bef98bb07fa3d42259cf
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.*; public class cf347C{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); int[] arr =new int[n]; int max = -1; arr[0] = sc.nextInt(); int prev = arr[0]; if(max < arr[0]) max = arr[0]; for(int i=1; i<n; i++) { arr[i] = sc.nextInt(); prev = gcd(prev, arr[i]); if(arr[i] > max) max = arr[i]; } int count = max/prev - n; //System.out.println(max+" "+prev+" "+count); if(count %2 == 1) System.out.println("Alice"); else System.out.println("Bob"); } public static int gcd(int a, int b) { if(a==0 || a==b) return b; if(b==0) return a; return gcd(b%a, a); } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
33339f45a9de5c2304cba51b456abee6
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.Scanner; public class C { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; a[0]=sc.nextInt(); a[1]= sc.nextInt(); int max = Math.max(a[0], a[1]); int t = NOD(a[0], a[1]); if (t==0){ for (int i=2; i<n; i++){ a[i] = sc.nextInt(); if (a[i]>max) max = a[i]; } if ((max-n)%2==0) System.out.println("Bob"); else System.out.println("Alice"); } else{ boolean flag = true; for (int i=2; i<n; i++){ a[i] = sc.nextInt(); if (a[i]%t!=0){ t = NOD(a[i], t); if (t==0) flag = false; } if (a[i]>max) max = a[i]; } if (flag){ if ((max/t-n)%2==0) System.out.println("Bob"); else System.out.println("Alice"); } else{ if ((max-n)%2==0) System.out.println("Bob"); else System.out.println("Alice"); } } } static int NOD(int n, int m){ if (n!=0) return NOD(m%n, n); return m; } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output
PASSED
82f9b49a16880afd2a811061e9fad47d
train_002.jsonl
1379691000
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.TreeSet; public class L { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); TreeSet<Integer> nums = new TreeSet<Integer>(); for(int i = 0; i < n; i++) { nums.add(in.nextInt()); } long gcd = nums.first(); for(int a : nums) { gcd = gcd(gcd, a); } System.out.println(((nums.last() / gcd) - nums.size()) % 2 == 0 ? "Bob" : "Alice"); } public static long gcd(long a, long b) { if(b == 0) { return a; } else { return gcd(b, a % b); } } }
Java
["2\n2 3", "2\n5 3", "3\n5 6 7"]
2 seconds
["Alice", "Alice", "Bob"]
NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Java 6
standard input
[ "number theory", "games", "math" ]
3185ae6b4b681a10a21d02e67f08fd19
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.
1,600
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
standard output