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
52e6511b737931c9d96d422f7d39e297
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; /** * Created by jizhe on 2016/1/21. */ public class DivisionIntoTeams { public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } private static class Node implements Comparable<Node> { int order, skill; public Node(int order, int skill) { this.order = order; this.skill = skill; } public int compareTo(Node another) { return Integer.compare(this.skill, another.skill); } } public static void main(String[] args) { //Scanner in = new Scanner(new BufferedInputStream(System.in)); FasterScanner in = new FasterScanner(); StringBuilder out = new StringBuilder(); int N = in.nextInt(); Node[] a = new Node[N]; for( int i = 0; i < N; i++ ) { a[i] = new Node(i+1, in.nextInt()); } Arrays.sort(a); int n1 = (N+1)/2; out.append(n1+"\n"); for( int i = 0; i < N; i += 2 ) { out.append(a[i].order+" "); } out.append("\n"); out.append(N-n1+"\n"); for( int i = 1; i < N; i += 2 ) { out.append(a[i].order+" "); } out.append("\n"); System.out.printf("%s\n", out.toString()); } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
9c8225a09b6f177f6021f5b1b8eac507
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class Main { private static class Pair { int val; int idx; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pr = new PrintWriter(System.out); int n = sc.nextInt(); List<Pair> boys = new ArrayList<>(); for(int i=0; i<n; i++) { Pair boy = new Pair(); boy.val = sc.nextInt(); boy.idx = i + 1; boys.add(boy); } Collections.sort(boys, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return Integer.compare(o1.val, o2.val); } }); List<Pair> listA = new ArrayList<>(); List<Pair> listB = new ArrayList<>(); List<Pair> target = listB; int mid = n%2==0 ? -1 : n/2; for(int i=0; i<n; i++) { if(i == mid) { listB.add(boys.get(i)); } else { target.add(boys.get(i)); if(target == listA) target = listB; else target = listA; } } StringBuilder sb = new StringBuilder(); buildResult(sb, listA); buildResult(sb, listB); pr.print(sb.toString()); pr.close(); sc.close(); } private static void buildResult(StringBuilder sb, List<Pair> list) { sb.append(list.size() + "\n"); for(int i=0; i<list.size(); i++) { sb.append(list.get(i).idx + " "); } sb.append("\n"); } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
c252661e5617445d8e34c2db0da5ebfa
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.nio.channels.ShutdownChannelGroupException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(), x = 0, y = 0; Pair [] a = new Pair[n]; for (int i = 0; i < a.length; i++) { a[i] = new Pair(bf.nextInt(), i+1); } Arrays.sort(a); StringBuilder ev = new StringBuilder(); StringBuilder odd = new StringBuilder(); for (int i = 0; i < a.length; i++) { if((i & 1) == 0) { ev.append(a[i].ind).append(" "); x++; } else { odd.append(a[i].ind).append(" "); y++; } } out.println(x); out.println(ev); out.println(y); out.println(odd); out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int val, ind; public Pair(int v, int i) { val = v; ind = i; } @Override public int compareTo(Pair o) { return val - o.val; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
b926935de4124af10d510464abcbd1db
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class JavaApplication7 { static String fixedLengthString(String string, int length) { return String.format("%1$"+length+ "s", string); } static boolean cas(char c) { char ar [] = {'A', 'E', 'I', 'O', 'U','Y'} ; for(int i = 0 ; i < ar.length ; i++) if(ar[i] == c) return true ; return false ; } static StringBuilder ans = new StringBuilder() ; static int ind = -1 ; static int count = 0; static void print(int ar []) { ind++; int max = -3; for(int x = 0 ; x <= ar.length-1 ; x++) max = Math.max(max, ar[x]) ; for(int z = 0 ; z <= ar.length-1 ; z++ ) { if(max == ar[z] ) { if(z + 1 <= ar.length -1 && max > ar[z+1]) { for(int w = z ; w < ar.length-1 ; w++ ) ans.append((z+1+ind) +" R\n"); for(int w= z ; w > 0 ; w--) ans.append((w+1+ind) +" L\n"); count++; return ; } if(z - 1 >= 0 && max > ar[z-1]) { for(int w= z ; w > 0 ; w--) ans.append((w+1+ind) +" L\n"); for(int w = z ; w < ar.length -1 ; w++) ans.append((ind+1) +" R\n"); count++; return ; } } } if(ar.length == 1) { count++; } } static int get(int n ) { String a = "1" ; for(int i = 0 ; i < n ;i++) a += "0" ; return Integer.parseInt(a) ; } static int ar [] ; public static void main(String[] args) throws Exception { Reader.init(System.in); int n = Reader.nextInt(); pair ar [] = new pair [n] ; for(int i = 0 ; i < n ; i++) ar[i] = new pair(Reader.nextInt() , i+1) ; Arrays.sort(ar); StringBuilder ans1 = new StringBuilder() , ans2 = new StringBuilder() ; int countT1 = 0 , countT2 = 0; for(int i = 0 ; i < n ; i++) { if(i % 2 == 0) { countT1++; ans1.append(ar[i].b+" ") ; } else { countT2++ ; ans2.append(ar[i].b + " ") ; } } System.out.println(countT1); System.out.println(ans1); System.out.println(countT2); System.out.println(ans2); } } class pair implements Comparable<pair> { int a , b; pair(int a , int b) { this.a = a ; this.b = b ; } public int compareTo(pair t) { if(t.a <a) return 1 ; else if(t.a > a) return -1 ; else return 0 ; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(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 Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()) ; } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
800f79d61b35cf19eb81eabd906b0aa8
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
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)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; //PrintWriter pw = new PrintWriter("output.out", "UTF-8"); int n = parseInt(in.readLine()); List<play> l = new ArrayList<play>(); tk = new StringTokenizer(in.readLine()); for(int i=0; i<n; i++) l.add(new play(i+1,parseInt(tk.nextToken()))); Collections.sort(l); List<Integer> a = new ArrayList<Integer>(); List<Integer> b = new ArrayList<Integer>(); a.add(l.get(0).num); b.add(l.get(n-1).num); int A = l.get(0).skill; int B = l.get(n-1).skill; for(int i=n-2; i>=1; i--) { if(a.size() > b.size()) { b.add(l.get(i).num); B += l.get(i).skill; } else if(a.size() < b.size()) { a.add(l.get(i).num); A += l.get(i).skill; } else if(A>=B) { b.add(l.get(i).num); B += l.get(i).skill; } else { a.add(l.get(i).num); A += l.get(i).skill; } } out.append(a.size()).append("\n"); out.append(a.get(0)); for(int i=1; i<a.size(); i++) out.append(" ").append(a.get(i)); out.append("\n").append(b.size()).append("\n"); out.append(b.get(0)); for(int i=1; i<b.size(); i++) out.append(" ").append(b.get(i)); System.out.println(out); } } class play implements Comparable<play> { int num,skill; public play(int n,int s) { this.num = n; this.skill = s; } @Override public int compareTo(play p) { if(skill != p.skill) return skill-p.skill; return num-p.num; } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
2808ccda4178fea60554f8135e7d9080
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
import java.io.*; import java.util.*; public class Main { int INF = (int)1e9; int MOD = 1000000007; void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int[][] a = new int[n][2]; for(int i=0; i<n; i++) { a[i][0] = in.nextInt(); a[i][1] = i; } ArrayList<Integer> ze = new ArrayList<>(); ArrayList<Integer> on = new ArrayList<>(); Arrays.sort(a, new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); for(int i=0; i<n; i++) { if(i%2==0) { ze.add(a[i][1]+1); } else { on.add(a[i][1]+1); } } out.println(ze.size()); for(int i=0; i<ze.size(); i++) { out.print(ze.get(i)+" "); } out.println(); out.println(on.size()); for(int i=0; i<on.size(); i++) { out.print(on.get(i)+" "); } out.println(); } public static void main(String[] args) throws IOException { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1;//in.nextInt(); while(t-- >0) { new Main().solve(in, out); } out.close(); } static class InputReader { static BufferedReader br; static StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
7628051a1994666f1fdd04610f96fe20
train_002.jsonl
1328886000
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static class FastScanner implements Closeable { BufferedReader in; StringTokenizer st; FastScanner() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } public void close() throws IOException { in.close(); st = null; } } public static void main(String[] args) throws IOException{ try(FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out)){ int n = sc.nextInt(); ArrayList <Pair> al = new ArrayList < > (); for(int i = 1; i <= n; i++){ al.add(new Pair(sc.nextInt(), i)); } Collections.sort(al, new Comparator <Pair> (){ public int compare(Pair a, Pair b){ return b.val - a.val; } }); int even = (int)Math.ceil(n / 2.0); int odd = (int)Math.floor(n / 2); out.println(even); for(int i = 0; i < n; i+= 2) out.print(al.get(i).pos+" "); out.println(""); out.println(odd); for(int i = 1; i < n; i+= 2) out.print(al.get(i).pos+" "); out.println(""); } } } class Pair{ int val; int pos; public Pair(int val, int pos){ this.val = val; this.pos = pos; } }
Java
["3\n1 2 1", "5\n2 3 3 1 1"]
1 second
["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"]
NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Java 8
standard input
[ "sortings", "greedy", "math" ]
0937a7e2f912fc094cc4275fd47cd457
The first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills.
1,500
On the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
standard output
PASSED
d0479328731ded53860c802c5e3ecfc3
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class x1439B { static HashSet<Integer>[] edges; public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); matcha:while(T-->0) { int N = infile.nextInt(); int M = infile.nextInt(); int K = infile.nextInt(); edges = new HashSet[N+1]; for(int i=1; i <= N; i++) edges[i] = new HashSet<Integer>(); for(int i=0; i < M; i++) { int a = infile.nextInt(); int b = infile.nextInt(); edges[a].add(b); edges[b].add(a); } TreeSet<Integer> bst = new TreeSet<Integer>((x,y) -> { if(edges[x].size() == edges[y].size()) return x-y; return edges[x].size()-edges[y].size(); }); for(int v=1; v <= N; v++) bst.add(v); while(bst.size() > 0) { int curr = bst.first(); if(edges[curr].size() >= K) { ArrayList<Integer> group = new ArrayList<Integer>(); for(int v=1; v <= N; v++) if(edges[v].size() >= K) group.add(v); sb.append("1 "+group.size()+"\n"); for(int v: group) sb.append(v+" "); sb.append("\n"); continue matcha; } else if(edges[curr].size() == K-1) { ArrayList<Integer> clique = new ArrayList<Integer>(); clique.add(curr); for(int next: edges[curr]) clique.add(next); boolean works = true; lol:for(int i=0; i < clique.size(); i++) for(int j=i+1; j < clique.size(); j++) if(!edges[clique.get(i)].contains(clique.get(j))) { works = false; break lol; } if(works) { sb.append("2\n"); for(int v: edges[curr]) sb.append(v+" "); sb.append(curr+"\n"); continue matcha; } } bst.remove(curr); for(int next: edges[curr]) { bst.remove(next); edges[next].remove(curr); bst.add(next); } } sb.append("-1\n"); } System.out.print(sb); } } class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
e80b176d90cfa4becd50a5380e23eccd
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
// No sorcery shall prevail. // import java.util.*; import java.io.*; public class _InVoker_ { //Variables static long mod2 = 1000000007; static long mod = 998244353; static FastReader inp= new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String args[]) { _InVoker_ g=new _InVoker_(); g.main(); out.close(); } //Main void main() { int t=inp.nextInt(); loop: while(t-->0) { int n=inp.nextInt(); int m=inp.nextInt(); int k=inp.nextInt(); HashSet<Integer> edges[]=new HashSet[n]; for(int i=0;i<n;i++) edges[i]=new HashSet<>(); Vertex nodes[]=new Vertex[n]; for(int i=0;i<n;i++) nodes[i]=new Vertex(i); for(int i=0;i<m;i++) { Vertex x=nodes[inp.nextInt()-1]; Vertex y=nodes[inp.nextInt()-1]; x.list.add(y); y.list.add(x); x.deg++; y.deg++; edges[x.idx].add(y.idx); edges[y.idx].add(x.idx); } if((k*(k-1))/2>m) { out.println(-1); continue loop; } TreeSet<Vertex> set=new TreeSet<>(); for(int i=0;i<n;i++) set.add(nodes[i]); Vertex near[]=new Vertex[n]; while(!set.isEmpty()) { Vertex cur=set.pollFirst(); if(cur.deg>=k) { set.add(cur); out.println(1+" "+set.size()); for(Vertex x: set) out.print((x.idx+1)+" "); out.println(); continue loop; } int c=0; cur.deleted=true; for(Vertex x: cur.list) { if(x.deleted) continue; if(x.deg>=k-1) { near[c++]=x; } set.remove(x); x.deg--; set.add(x); } if(c==k-1) { boolean clique=true; for(int i=0;i<k-1 && clique;i++) { for(int j=0;j<i;j++) { if(!edges[near[i].idx].contains(near[j].idx)) { clique=false; break; } } } if(clique) { out.println(2); out.print(cur.idx+1); for(int i=0;i<c;i++) out.print(" "+(near[i].idx+1)); out.println(); continue loop; } } } out.println(-1); } } long LONG_TO_INT_MASK = (1L << 32) - 1; long hash(int x, int y) { if(x>y) { int temp=x; x=y; y=temp; } return (((long) x) << 32) | (((long) y) & LONG_TO_INT_MASK); } class Vertex implements Comparable<Vertex>{ int idx,deg; ArrayList<Vertex> list; boolean deleted=false; Vertex(int i){ this.idx=i; deg=0; list=new ArrayList<>(); } public int compareTo(Vertex o) { return deg==o.deg?Integer.compare(idx, o.idx):Integer.compare(deg, o.deg); } } /********************************************************************************************************************************************************************************************************* * ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE* *ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE * *ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE * *ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE * *ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE * *ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE * *ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD * *ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE * *ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD * *ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD * *ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD * *ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD * *ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD * *ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD * *ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD * *tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD * *tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE * *ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD * *tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD * *ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD * *tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD * *ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD * *tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD * *tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD * *tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD * *tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD * *tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD * *tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD * *tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD * *tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD * *tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD * *tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD * *tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD * *tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD * *jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD * *tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD * *tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD * *jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD * *jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD * *jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD * *jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD * *jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD * *jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD * *jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD * *jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD * *jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD * *jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD * *jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD * *jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD * *jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD * *jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD * *jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD * *jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD * *jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD * *jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED * *jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE * *jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD * *jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG * *jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG * *jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG * *jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG * *jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG * *fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL * *fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL * *fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL * *fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG * *fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG * *fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG * *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG * *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD * *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD * *fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD * *fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD * *fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD * *fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD * *fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD * *jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD * *fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG * *fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; * *fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, * *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, * *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, * *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; * ***********************************************************************************************************************************************************************************************************/ void sort(int a[]) { ArrayList<Integer> list=new ArrayList<>(); for(int x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void sort(long a[]) { ArrayList<Long> list=new ArrayList<>(); for(long x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void ruffleSort(int a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); int temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } void ruffleSort(long a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); long temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } 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 s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } long fact[]; long invFact[]; void init(int n) { fact=new long[n+1]; invFact=new long[n+1]; fact[0]=1; for(int i=1;i<=n;i++) { fact[i]=mul(i,fact[i-1]); } invFact[n]=power(fact[n],mod-2); for(int i=n-1;i>=0;i--) { invFact[i]=mul(invFact[i+1],i+1); } } long nCr(int n, int r) { if(n<r || r<0) return 0; return mul(fact[n],mul(invFact[r],invFact[n-r])); } long mul(long a, long b) { return a*b%mod; } long add(long a, long b) { return (a+b)%mod; } long power(long x, long y) { long gg=1; while(y>0) { if(y%2==1) gg=mul(gg,x); x=mul(x,x); y/=2; } return gg; } // Functions static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } static int gcd(int a, int b) { return b==0?a:gcd(b,a%b); } void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } //Input Arrays static void input(long a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextLong(); } } static void input(int a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextInt(); } } static void input(String s[],int n) { for(int i=0;i<n;i++) { s[i]=inp.next(); } } static void input(int a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextInt(); } } } static void input(long a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextLong(); } } } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
f409fb3a77412c2f750cf5bc004537c3
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { Heap heap = new Heap(n, (i, j) -> Integer.compare(graph[i].size(), graph[j].size()), n); heap.addAll(Range.range(n)); while (!heap.isEmpty() && graph[heap.peek()].size() < k) { int u = heap.poll(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); graph[v].remove(u); heap.shiftUp(heap.getIndex(v)); } } if (heap.isEmpty()) { out.printLine(-1); } else { int[] res = heap.toArray(); MiscUtils.increaseByOne(res); out.printLine(1, heap.size()); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static interface IntQueue extends IntCollection { } static class Heap implements IntQueue { private IntComparator comparator; private int size = 0; private int[] elements; private int[] at; public Heap(int maxElement) { this(10, maxElement); } public Heap(IntComparator comparator, int maxElement) { this(10, comparator, maxElement); } public Heap(int capacity, int maxElement) { this(capacity, IntComparator.DEFAULT, maxElement); } public Heap(int capacity, IntComparator comparator, int maxElement) { this.comparator = comparator; elements = new int[capacity]; at = new int[maxElement]; Arrays.fill(at, -1); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void add(int element) { ensureCapacity(size + 1); elements[size] = element; at[element] = size; shiftUp(size++); } public void shiftUp(int index) { // if (index < 0 || index >= size) // throw new IllegalArgumentException(); int value = elements[index]; while (index != 0) { int parent = (index - 1) >>> 1; int parentValue = elements[parent]; if (comparator.compare(parentValue, value) <= 0) { elements[index] = value; at[value] = index; return; } elements[index] = parentValue; at[parentValue] = index; index = parent; } elements[0] = value; at[value] = 0; } public void shiftDown(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException(); } while (true) { int child = (index << 1) + 1; if (child >= size) { return; } if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) { child++; } if (comparator.compare(elements[index], elements[child]) <= 0) { return; } swap(index, child); index = child; } } public int getIndex(int element) { return at[element]; } private void swap(int first, int second) { int temp = elements[first]; elements[first] = elements[second]; elements[second] = temp; at[elements[first]] = first; at[elements[second]] = second; } private void ensureCapacity(int size) { if (elements.length < size) { int[] oldElements = elements; elements = new int[Math.max(2 * elements.length, size)]; System.arraycopy(oldElements, 0, elements, 0, this.size); } } public int peek() { if (isEmpty()) { throw new IndexOutOfBoundsException(); } return elements[0]; } public int poll() { if (isEmpty()) { throw new IndexOutOfBoundsException(); } int result = elements[0]; at[result] = -1; if (size == 1) { size = 0; return result; } elements[0] = elements[--size]; at[elements[0]] = 0; shiftDown(0); return result; } public IntIterator intIterator() { return new IntIterator() { private int at; public int value() throws NoSuchElementException { return elements[at]; } public boolean advance() throws NoSuchElementException { return ++at < size; } public boolean isValid() { return at < size; } public void remove() throws NoSuchElementException { throw new UnsupportedOperationException(); } }; } } static interface EzIntIterator { boolean hasNext(); int next(); } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface IntCollection extends egork_generated_collections_IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(egork_generated_collections_IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static interface IntReversableCollection extends IntCollection { } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; private int[] table; private byte[] status; private int size; private int removedCount; private int mask; private final int hashSeed; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static abstract class IntAbstractStream implements egork_generated_collections_IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof egork_generated_collections_IntStream)) { return false; } egork_generated_collections_IntStream c = (egork_generated_collections_IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } public static IntList range(int n) { return range(0, n); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); boolean equals(Object object); int hashCode(); String toString(); } static interface egork_generated_collections_IntStream extends Iterable<Integer>, Comparable<egork_generated_collections_IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(egork_generated_collections_IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntComparator { IntComparator DEFAULT = Integer::compare; int compare(int first, int second); } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
ce5daa788cb0daa819637ccaec7f1095
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.Random; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { EzIntQueue queue = new EzIntArrayDeque(); boolean[] used = new boolean[n]; for (int i = 0; i < n; i++) { if (graph[i].size() < k) { queue.add(i); used[i] = true; } } while (!queue.isEmpty()) { int u = queue.removeFirst(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); if (graph[v].size() == k) { queue.add(v); used[v] = true; } graph[v].remove(u); } graph[u].clear(); } if (ArrayUtils.count(used, false) == 0) { out.printLine(-1); } else { int[] res = IntStream.range(0, n).filter(i -> !used[i]).toArray(); MiscUtils.increaseByOne(res); out.printLine(1, res.length); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static interface EzIntDeque extends EzIntQueue, EzIntStack { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static interface EzIntIterator { boolean hasNext(); int next(); } static class ArrayUtils { public static int count(boolean[] array, boolean value) { int result = 0; for (boolean i : array) { if (i == value) { result++; } } return result; } } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface EzIntQueue extends EzIntCollection { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static interface EzIntList extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static interface EzIntStack extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class EzIntArrayDeque implements EzIntDeque, EzIntList { private static final int DEFAULT_CAPACITY = 8; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private int[] deque; private int size; private int head; private int tail; private int mask; public EzIntArrayDeque() { this(DEFAULT_CAPACITY); } public EzIntArrayDeque(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } if (capacity < 1) { capacity = 1; } if ((capacity & (capacity - 1)) != 0) { capacity = Integer.highestOneBit(capacity) << 1; } // Capacity is a power of 2 now deque = new int[capacity]; size = 0; head = 0; tail = 0; mask = deque.length - 1; } public EzIntArrayDeque(EzIntCollection collection) { this(collection.size() + 1); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { deque[tail++] = iterator.next(); } size = collection.size(); } public EzIntArrayDeque(int[] srcArray) { this(srcArray.length + 1); System.arraycopy(srcArray, 0, deque, 0, srcArray.length); tail = srcArray.length; size = srcArray.length; } public EzIntArrayDeque(Collection<Integer> javaCollection) { this(javaCollection.size() + 1); for (int element : javaCollection) { deque[tail++] = element; } size = javaCollection.size(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public EzIntIterator iterator() { return new EzIntArrayDequeIterator(); } public boolean add(int element) { deque[tail] = element; tail = (tail + 1) & mask; size++; if (size == deque.length) { enlarge(); } return true; } public int removeFirst() { if (size == 0) { throw new NoSuchElementException("Trying to call removeFirst() on empty ArrayDeque"); } final int removedElement = deque[head]; size--; head = (head + 1) & mask; return removedElement; } private void enlarge() { int newSize = (size << 1); int[] newArray = new int[newSize]; System.arraycopy(deque, head, newArray, 0, deque.length - head); System.arraycopy(deque, 0, newArray, deque.length - tail, tail); deque = newArray; head = 0; tail = size; mask = deque.length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntArrayDeque that = (EzIntArrayDeque) o; if (size != that.size) { return false; } for (int i = head, j = that.head; i != tail; i = (i + 1) & mask, j = (j + 1) & that.mask) { if (deque[i] != that.deque[j]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int i = head; i != tail; i = (i + 1) & mask) { hash = (hash ^ PrimitiveHashCalculator.getHash(deque[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = head; i != tail; i = (i + 1) & mask) { if (i != head) { sb.append(", "); } sb.append(deque[i]); } sb.append(']'); return sb.toString(); } private class EzIntArrayDequeIterator implements EzIntIterator { private int curIndex = head; public boolean hasNext() { return curIndex != tail; } public int next() { if (curIndex == tail) { throw new NoSuchElementException("Iterator doesn't have more elements"); } final int result = deque[curIndex]; curIndex = (curIndex + 1) & mask; return result; } } } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; private int[] table; private byte[] status; private int size; private int removedCount; private int mask; private final int hashSeed; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } public void clear() { if (table.length > REBUILD_LENGTH_THRESHOLD) { initEmptyTable(REBUILD_LENGTH_THRESHOLD); } else { Arrays.fill(status, FREE); size = 0; removedCount = 0; } } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); void clear(); boolean equals(Object object); int hashCode(); String toString(); } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
610f926232a262cbec493b7f7e44d6ba
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { Heap heap = new Heap(n, (i, j) -> Integer.compare(graph[i].size(), graph[j].size()), n); heap.addAll(Range.range(n)); while (!heap.isEmpty() && graph[heap.peek()].size() < k) { int u = heap.poll(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); graph[v].remove(u); heap.shiftUp(heap.getIndex(v)); } } if (heap.isEmpty()) { out.printLine(-1); } else { int[] res = heap.toArray(); MiscUtils.increaseByOne(res); out.printLine(1, heap.size()); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static interface IntQueue extends IntCollection { } static class Heap implements IntQueue { private IntComparator comparator; private int size = 0; private int[] elements; private int[] at; public Heap(int maxElement) { this(10, maxElement); } public Heap(IntComparator comparator, int maxElement) { this(10, comparator, maxElement); } public Heap(int capacity, int maxElement) { this(capacity, IntComparator.DEFAULT, maxElement); } public Heap(int capacity, IntComparator comparator, int maxElement) { this.comparator = comparator; elements = new int[capacity]; at = new int[maxElement]; Arrays.fill(at, -1); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void add(int element) { ensureCapacity(size + 1); elements[size] = element; at[element] = size; shiftUp(size++); } public void shiftUp(int index) { // if (index < 0 || index >= size) // throw new IllegalArgumentException(); int value = elements[index]; while (index != 0) { int parent = (index - 1) >>> 1; int parentValue = elements[parent]; if (comparator.compare(parentValue, value) <= 0) { elements[index] = value; at[value] = index; return; } elements[index] = parentValue; at[parentValue] = index; index = parent; } elements[0] = value; at[value] = 0; } public void shiftDown(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException(); } while (true) { int child = (index << 1) + 1; if (child >= size) { return; } if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) { child++; } if (comparator.compare(elements[index], elements[child]) <= 0) { return; } swap(index, child); index = child; } } public int getIndex(int element) { return at[element]; } private void swap(int first, int second) { int temp = elements[first]; elements[first] = elements[second]; elements[second] = temp; at[elements[first]] = first; at[elements[second]] = second; } private void ensureCapacity(int size) { if (elements.length < size) { int[] oldElements = elements; elements = new int[Math.max(2 * elements.length, size)]; System.arraycopy(oldElements, 0, elements, 0, this.size); } } public int peek() { if (isEmpty()) { throw new IndexOutOfBoundsException(); } return elements[0]; } public int poll() { if (isEmpty()) { throw new IndexOutOfBoundsException(); } int result = elements[0]; at[result] = -1; if (size == 1) { size = 0; return result; } elements[0] = elements[--size]; at[elements[0]] = 0; shiftDown(0); return result; } public IntIterator intIterator() { return new IntIterator() { private int at; public int value() throws NoSuchElementException { return elements[at]; } public boolean advance() throws NoSuchElementException { return ++at < size; } public boolean isValid() { return at < size; } public void remove() throws NoSuchElementException { throw new UnsupportedOperationException(); } }; } } static interface EzIntIterator { boolean hasNext(); int next(); } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface IntCollection extends egork_generated_collections_IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(egork_generated_collections_IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static interface IntComparator { IntComparator DEFAULT = Integer::compare; int compare(int first, int second); } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntReversableCollection extends IntCollection { } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; private int[] table; private byte[] status; private int size; private int removedCount; private int mask; private final int hashSeed; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static abstract class IntAbstractStream implements egork_generated_collections_IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof egork_generated_collections_IntStream)) { return false; } egork_generated_collections_IntStream c = (egork_generated_collections_IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } public static IntList range(int n) { return range(0, n); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); boolean equals(Object object); int hashCode(); String toString(); } static interface egork_generated_collections_IntStream extends Iterable<Integer>, Comparable<egork_generated_collections_IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(egork_generated_collections_IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
2a8491f64b04468224d071bc9600caec
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.Random; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { EzIntQueue queue = new EzIntArrayDeque(); boolean[] used = new boolean[n]; for (int i = 0; i < n; i++) { if (graph[i].size() < k) { queue.add(i); used[i] = true; } } while (!queue.isEmpty()) { int u = queue.removeFirst(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); if (graph[v].size() == k) { queue.add(v); used[v] = true; } graph[v].remove(u); } graph[u].clear(); } if (ArrayUtils.count(used, false) == 0) { out.printLine(-1); } else { EzIntList list = new EzIntArrayList(); for (int i = 0; i < n; i++) { if (!used[i]) { list.add(i); } } int[] res = list.toArray(); MiscUtils.increaseByOne(res); out.printLine(1, res.length); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static class ArrayUtils { public static int count(boolean[] array, boolean value) { int result = 0; for (boolean i : array) { if (i == value) { result++; } } return result; } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); void clear(); boolean equals(Object object); int hashCode(); String toString(); } static interface EzIntDeque extends EzIntQueue, EzIntStack { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static interface EzIntStack extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; private int[] table; private byte[] status; private int size; private int removedCount; private int mask; private final int hashSeed; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } public void clear() { if (table.length > REBUILD_LENGTH_THRESHOLD) { initEmptyTable(REBUILD_LENGTH_THRESHOLD); } else { Arrays.fill(status, FREE); size = 0; removedCount = 0; } } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static interface EzIntQueue extends EzIntCollection { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static interface EzIntList extends EzIntCollection { int size(); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); } static interface EzIntIterator { boolean hasNext(); int next(); } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static class EzIntArrayList implements EzIntList, EzIntStack { private static final int DEFAULT_CAPACITY = 10; private static final double ENLARGE_SCALE = 2.0; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private int[] array; private int size; public EzIntArrayList() { this(DEFAULT_CAPACITY); } public EzIntArrayList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } array = new int[capacity]; size = 0; } public EzIntArrayList(EzIntCollection collection) { size = collection.size(); array = new int[size]; int i = 0; for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { array[i++] = iterator.next(); } } public EzIntArrayList(int[] srcArray) { size = srcArray.length; array = new int[size]; System.arraycopy(srcArray, 0, array, 0, size); } public EzIntArrayList(Collection<Integer> javaCollection) { size = javaCollection.size(); array = new int[size]; int i = 0; for (int element : javaCollection) { array[i++] = element; } } public int size() { return size; } public EzIntIterator iterator() { return new EzIntArrayListIterator(); } public int[] toArray() { int[] result = new int[size]; System.arraycopy(array, 0, result, 0, size); return result; } public boolean add(int element) { if (size == array.length) { enlarge(); } array[size++] = element; return true; } private void enlarge() { int newSize = Math.max(size + 1, (int) (size * ENLARGE_SCALE)); int[] newArray = new int[newSize]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntArrayList that = (EzIntArrayList) o; if (size != that.size) { return false; } for (int i = 0; i < size; i++) { if (array[i] != that.array[i]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < size; i++) { sb.append(array[i]); if (i < size - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); } private class EzIntArrayListIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { return curIndex < size; } public int next() { if (curIndex == size) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return array[curIndex++]; } } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class EzIntArrayDeque implements EzIntDeque, EzIntList { private static final int DEFAULT_CAPACITY = 8; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private int[] deque; private int size; private int head; private int tail; private int mask; public EzIntArrayDeque() { this(DEFAULT_CAPACITY); } public EzIntArrayDeque(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } if (capacity < 1) { capacity = 1; } if ((capacity & (capacity - 1)) != 0) { capacity = Integer.highestOneBit(capacity) << 1; } // Capacity is a power of 2 now deque = new int[capacity]; size = 0; head = 0; tail = 0; mask = deque.length - 1; } public EzIntArrayDeque(EzIntCollection collection) { this(collection.size() + 1); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { deque[tail++] = iterator.next(); } size = collection.size(); } public EzIntArrayDeque(int[] srcArray) { this(srcArray.length + 1); System.arraycopy(srcArray, 0, deque, 0, srcArray.length); tail = srcArray.length; size = srcArray.length; } public EzIntArrayDeque(Collection<Integer> javaCollection) { this(javaCollection.size() + 1); for (int element : javaCollection) { deque[tail++] = element; } size = javaCollection.size(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public EzIntIterator iterator() { return new EzIntArrayDequeIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = head, j = 0; i != tail; i = (i + 1) & mask) { result[j++] = deque[i]; } return result; } public boolean add(int element) { deque[tail] = element; tail = (tail + 1) & mask; size++; if (size == deque.length) { enlarge(); } return true; } public int removeFirst() { if (size == 0) { throw new NoSuchElementException("Trying to call removeFirst() on empty ArrayDeque"); } final int removedElement = deque[head]; size--; head = (head + 1) & mask; return removedElement; } private void enlarge() { int newSize = (size << 1); int[] newArray = new int[newSize]; System.arraycopy(deque, head, newArray, 0, deque.length - head); System.arraycopy(deque, 0, newArray, deque.length - tail, tail); deque = newArray; head = 0; tail = size; mask = deque.length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntArrayDeque that = (EzIntArrayDeque) o; if (size != that.size) { return false; } for (int i = head, j = that.head; i != tail; i = (i + 1) & mask, j = (j + 1) & that.mask) { if (deque[i] != that.deque[j]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int i = head; i != tail; i = (i + 1) & mask) { hash = (hash ^ PrimitiveHashCalculator.getHash(deque[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = head; i != tail; i = (i + 1) & mask) { if (i != head) { sb.append(", "); } sb.append(deque[i]); } sb.append(']'); return sb.toString(); } private class EzIntArrayDequeIterator implements EzIntIterator { private int curIndex = head; public boolean hasNext() { return curIndex != tail; } public int next() { if (curIndex == tail) { throw new NoSuchElementException("Iterator doesn't have more elements"); } final int result = deque[curIndex]; curIndex = (curIndex + 1) & mask; return result; } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
5695294377103e857bb9a40aa10113f7
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.Random; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { EzIntQueue queue = new EzIntArrayDeque(); boolean[] used = new boolean[n]; for (int i = 0; i < n; i++) { if (graph[i].size() < k) { queue.add(i); used[i] = true; } } while (!queue.isEmpty()) { int u = queue.removeFirst(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); if (graph[v].size() == k) { queue.add(v); used[v] = true; } graph[v].remove(u); } graph[u].clear(); } if (ArrayUtils.count(used, false) == 0) { out.printLine(-1); } else { int[] res = IntStream.range(0, n).filter(i -> !used[i]).toArray(); MiscUtils.increaseByOne(res); out.printLine(1, res.length); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static interface EzIntDeque extends EzIntQueue, EzIntStack { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static interface EzIntIterator { boolean hasNext(); int next(); } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static class ArrayUtils { public static int count(boolean[] array, boolean value) { int result = 0; for (boolean i : array) { if (i == value) { result++; } } return result; } } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface EzIntQueue extends EzIntCollection { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int removeFirst(); } static interface EzIntList extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static interface EzIntStack extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class EzIntArrayDeque implements EzIntDeque, EzIntList { private static final int DEFAULT_CAPACITY = 8; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private int[] deque; private int size; private int head; private int tail; private int mask; public EzIntArrayDeque() { this(DEFAULT_CAPACITY); } public EzIntArrayDeque(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } if (capacity < 1) { capacity = 1; } if ((capacity & (capacity - 1)) != 0) { capacity = Integer.highestOneBit(capacity) << 1; } // Capacity is a power of 2 now deque = new int[capacity]; size = 0; head = 0; tail = 0; mask = deque.length - 1; } public EzIntArrayDeque(EzIntCollection collection) { this(collection.size() + 1); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { deque[tail++] = iterator.next(); } size = collection.size(); } public EzIntArrayDeque(int[] srcArray) { this(srcArray.length + 1); System.arraycopy(srcArray, 0, deque, 0, srcArray.length); tail = srcArray.length; size = srcArray.length; } public EzIntArrayDeque(Collection<Integer> javaCollection) { this(javaCollection.size() + 1); for (int element : javaCollection) { deque[tail++] = element; } size = javaCollection.size(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public EzIntIterator iterator() { return new EzIntArrayDequeIterator(); } public boolean add(int element) { deque[tail] = element; tail = (tail + 1) & mask; size++; if (size == deque.length) { enlarge(); } return true; } public int removeFirst() { if (size == 0) { throw new NoSuchElementException("Trying to call removeFirst() on empty ArrayDeque"); } final int removedElement = deque[head]; size--; head = (head + 1) & mask; return removedElement; } private void enlarge() { int newSize = (size << 1); int[] newArray = new int[newSize]; System.arraycopy(deque, head, newArray, 0, deque.length - head); System.arraycopy(deque, 0, newArray, deque.length - tail, tail); deque = newArray; head = 0; tail = size; mask = deque.length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntArrayDeque that = (EzIntArrayDeque) o; if (size != that.size) { return false; } for (int i = head, j = that.head; i != tail; i = (i + 1) & mask, j = (j + 1) & that.mask) { if (deque[i] != that.deque[j]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int i = head; i != tail; i = (i + 1) & mask) { hash = (hash ^ PrimitiveHashCalculator.getHash(deque[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = head; i != tail; i = (i + 1) & mask) { if (i != head) { sb.append(", "); } sb.append(deque[i]); } sb.append(']'); return sb.toString(); } private class EzIntArrayDequeIterator implements EzIntIterator { private int curIndex = head; public boolean hasNext() { return curIndex != tail; } public int next() { if (curIndex == tail) { throw new NoSuchElementException("Iterator doesn't have more elements"); } final int result = deque[curIndex]; curIndex = (curIndex + 1) & mask; return result; } } } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; private static final int POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; private static final int STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; private static final int STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; private int[] table = null; private byte[] status = null; private int size; private int removedCount; private int mask; private final int hashSeed; public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } public void clear() { if (table.length > REBUILD_LENGTH_THRESHOLD) { initEmptyTable(REBUILD_LENGTH_THRESHOLD); } else { Arrays.fill(status, FREE); size = 0; removedCount = 0; } } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); void clear(); boolean equals(Object object); int hashCode(); String toString(); } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
96106fb563fcb77418000d74a0bbb1b9
train_002.jsonl
1605623700
You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); BGraphSubsetProblem solver = new BGraphSubsetProblem(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BGraphSubsetProblem { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); int[] u = new int[m], v = new int[m]; in.readIntArrays(u, v); MiscUtils.decreaseByOne(u, v); EzIntSet[] graph = createGraph(n, m, u, v); solve(n, graph, k, out); } void solve(int n, EzIntSet[] graph, int k, OutputWriter out) { EzIntCustomTreeSet set = new EzIntCustomTreeSet(Range.range(n).toArray(), (i, j) -> graph[i].size() != graph[j].size() ? Integer.compare(graph[i].size(), graph[j].size()) : Integer.compare(i, j)); while (!set.isEmpty() && graph[set.getFirst()].size() < k) { int u = set.removeFirst(); if (graph[u].size() == k - 1 && checkClique(u, graph)) { int[] res = new int[k]; res[0] = u; System.arraycopy(graph[u].toArray(), 0, res, 1, k - 1); MiscUtils.increaseByOne(res); out.printLine(2); out.printLine(res); return; } for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); set.remove(v); graph[v].remove(u); set.add(v); } graph[u].clear(); } if (set.isEmpty()) { out.printLine(-1); } else { int[] res = set.toArray(); MiscUtils.increaseByOne(res); out.printLine(1, set.size()); out.printLine(res); } } boolean checkClique(int u, EzIntSet[] graph) { for (EzIntIterator it = graph[u].iterator(); it.hasNext(); ) { int v = it.next(); for (EzIntIterator it2 = graph[u].iterator(); it2.hasNext(); ) { int w = it2.next(); if (v != w && !graph[v].contains(w)) { return false; } } } return true; } EzIntSet[] createGraph(int n, int m, int[] u, int[] v) { EzIntSet[] res = new EzIntSet[n]; Arrays.setAll(res, i -> new EzIntHashSet(0)); for (int i = 0; i < m; i++) { res[u[i]].add(v[i]); res[v[i]].add(u[i]); } return res; } } static interface EzIntIterator { boolean hasNext(); int next(); } 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 print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static interface IntCollection extends egork_generated_collections_IntStream { public int size(); default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } public static IntList range(int n) { return range(0, n); } } static class EzIntHashSet implements EzIntSet { private static final int DEFAULT_CAPACITY = 8; private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; private int[] table; private byte[] status; private int size; private int removedCount; private int mask; private final int hashSeed; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } public EzIntHashSet() { this(DEFAULT_CAPACITY); } public EzIntHashSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); hashSeed = rnd.nextInt(); } public EzIntHashSet(EzIntCollection collection) { this(collection.size()); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntHashSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntHashSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean contains(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return true; } } return false; } public EzIntIterator iterator() { return new EzIntHashSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, j = 0; i < table.length; i++) { if (status[i] == FILLED) { result[j++] = table[i]; } } return result; } public boolean add(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (table[pos] == element) { return false; } } if (status[pos] == FREE) { status[pos] = FILLED; table[pos] = element; size++; if ((size + removedCount) * 2 > table.length) { rebuild(table.length * 2); // enlarge the table } return true; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { return false; } } status[removedPos] = FILLED; table[removedPos] = element; size++; removedCount--; return true; } public boolean remove(int element) { final int elementHash = PrimitiveHashCalculator.getHash(element); int pos = getStartPos(elementHash); final int step = getStep(elementHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && table[pos] == element) { status[pos] = REMOVED; size--; removedCount++; if (table.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= table.length) { rebuild(table.length / 2); // compress the table } else if (size < removedCount) { rebuild(table.length); // just rebuild the table } } return true; } } return false; } public void clear() { if (table.length > REBUILD_LENGTH_THRESHOLD) { initEmptyTable(REBUILD_LENGTH_THRESHOLD); } else { Arrays.fill(status, FREE); size = 0; removedCount = 0; } } private void rebuild(int newLength) { int[] oldTable = table; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldTable.length; i++) { if (oldStatus[i] == FILLED) { add(oldTable[i]); } } } private void initEmptyTable(int length) { table = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntHashSet that = (EzIntHashSet) o; if (size != that.size) { return false; } for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (!that.contains(table[i])) { return false; } } } return true; } public int hashCode() { int[] array = toArray(); EzIntSort.sort(array); int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < table.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(table[i]); } } sb.append(']'); return sb.toString(); } private class EzIntHashSetIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } return curIndex < table.length; } public int next() { while (curIndex < table.length && status[curIndex] != FILLED) { curIndex++; } if (curIndex == table.length) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return table[curIndex++]; } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public void readIntArrays(int[]... arrays) { int length = (int) Arrays.stream(arrays[0]).count(); for (int i = 0; i < length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = readInt(); } } } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static interface EzIntSet extends EzIntCollection { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); void clear(); boolean equals(Object object); int hashCode(); String toString(); } static interface EzIntSortedSet extends EzIntSet { int size(); boolean contains(int element); EzIntIterator iterator(); int[] toArray(); boolean add(int element); boolean remove(int element); void clear(); boolean equals(Object object); int hashCode(); String toString(); } static interface IntReversableCollection extends IntCollection { } static class MiscUtils { public static void decreaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]--; } } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { decreaseByOne(array); } } public static void increaseByOne(int[] array) { for (int i = 0; i < array.length; i++) { array[i]++; } } } static interface egork_generated_collections_IntStream extends Iterable<Integer>, Comparable<egork_generated_collections_IntStream> { IntIterator intIterator(); default Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default int compareTo(egork_generated_collections_IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static abstract class IntAbstractStream implements egork_generated_collections_IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof egork_generated_collections_IntStream)) { return false; } egork_generated_collections_IntStream c = (egork_generated_collections_IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static final class EzIntSort { private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0; private static final Random rnd = new Random(); private EzIntSort() { } private static int maxQuickSortDepth(int length) { if (length <= 1) { return 0; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1; return (int) (HEAPSORT_DEPTH_COEFFICIENT * log); } public static void sort(int[] a) { quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length)); } private static void quickSort(int[] a, int left, int right, int depth, int maxDepth) { if (right - left <= 1) { return; } if (depth > maxDepth) { heapSort(a, left, right - left); return; } final int pivot = a[left + rnd.nextInt(right - left)]; int i = left; int j = right - 1; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { int tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } while (i <= j); quickSort(a, left, j + 1, depth + 1, maxDepth); quickSort(a, i, right, depth + 1, maxDepth); } private static void heapSort(int[] a, int offset, int size) { // If size <= 1, nothing is executed for (int i = (size >>> 1) - 1; i >= 0; i--) { down(a, i, offset, size); } for (int i = size - 1; i > 0; i--) { int tmp = a[offset]; a[offset] = a[offset + i]; a[offset + i] = tmp; down(a, 0, offset, i); } } private static void down(int[] a, int index, int offset, int size) { final int element = a[offset + index]; final int firstLeaf = (size >>> 1); while (index < firstLeaf) { int largestChild = (index << 1) + 1; if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) { largestChild++; } if (a[offset + largestChild] <= element) { break; } a[offset + index] = a[offset + largestChild]; index = largestChild; } a[offset + index] = element; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static interface EzIntComparator { int compare(int a, int b); } static class EzIntCustomTreeSet implements EzIntSortedSet { private static final int DEFAULT_CAPACITY = 10; private static final double ENLARGE_SCALE = 2.0; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final boolean BLACK = false; private static final boolean RED = true; private static final int NULL = 0; private static final int DEFAULT_NULL_ELEMENT = (new int[1])[0]; private int[] key; private int[] left; private int[] right; private int[] p; private boolean[] color; private int size; private int root; private boolean returnedNull; private EzIntComparator cmp; public EzIntCustomTreeSet(EzIntComparator cmp) { this(DEFAULT_CAPACITY, cmp); } public EzIntCustomTreeSet(int capacity, EzIntComparator cmp) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } this.cmp = cmp; capacity++; key = new int[capacity]; left = new int[capacity]; right = new int[capacity]; p = new int[capacity]; color = new boolean[capacity]; color[NULL] = BLACK; size = 0; root = NULL; returnedNull = false; } public EzIntCustomTreeSet(EzIntCollection collection, EzIntComparator cmp) { this(collection.size(), cmp); for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { add(iterator.next()); } } public EzIntCustomTreeSet(int[] srcArray, EzIntComparator cmp) { this(srcArray.length, cmp); for (int element : srcArray) { add(element); } } public EzIntCustomTreeSet(Collection<Integer> javaCollection, EzIntComparator cmp) { this(javaCollection.size(), cmp); for (int element : javaCollection) { add(element); } } public int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean contains(int element) { int x = root; while (x != NULL) { int cmpRes = cmp.compare(element, key[x]); if (cmpRes < 0) { x = left[x]; } else if (cmpRes > 0) { x = right[x]; } else { return true; } } return false; } public EzIntIterator iterator() { return new EzIntTreeSetIterator(); } public int[] toArray() { int[] result = new int[size]; for (int i = 0, x = firstNode(); x != NULL; x = successorNode(x), i++) { result[i] = key[x]; } return result; } public boolean add(int element) { int y = NULL; int x = root; while (x != NULL) { //noinspection SuspiciousNameCombination y = x; int cmpRes = cmp.compare(element, key[x]); if (cmpRes < 0) { x = left[x]; } else if (cmpRes > 0) { x = right[x]; } else { return false; } } if (size == color.length - 1) { enlarge(); } int z = ++size; key[z] = element; p[z] = y; if (y == NULL) { root = z; } else { if (cmp.compare(element, key[y]) < 0) { left[y] = z; } else { right[y] = z; } } left[z] = NULL; right[z] = NULL; color[z] = RED; fixAfterAdd(z); return true; } public boolean remove(int element) { int z = root; while (z != NULL) { int cmpRes = cmp.compare(element, key[z]); if (cmpRes < 0) { z = left[z]; } else if (cmpRes > 0) { z = right[z]; } else { removeNode(z); return true; } } return false; } private void removeNode(int z) { int y = (left[z] == NULL || right[z] == NULL) ? z : successorNode(z); int x = (left[y] != NULL) ? left[y] : right[y]; p[x] = p[y]; if (p[y] == NULL) { root = x; } else { if (y == left[p[y]]) { left[p[y]] = x; } else { right[p[y]] = x; } } if (y != z) { key[z] = key[y]; } //noinspection PointlessBooleanExpression if (color[y] == BLACK) { fixAfterRemove(x); } // Swap with last if (y != size) { // copy fields key[y] = key[size]; left[y] = left[size]; right[y] = right[size]; p[y] = p[size]; color[y] = color[size]; // fix the children's parents p[left[size]] = y; p[right[size]] = y; // fix one of the parent's children if (left[p[size]] == size) { left[p[size]] = y; } else { right[p[size]] = y; } // fix root if (root == size) { root = y; } } size--; } private int successorNode(int x) { if (right[x] != NULL) { x = right[x]; while (left[x] != NULL) { x = left[x]; } return x; } else { int y = p[x]; while (y != NULL && x == right[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } return y; } } private void fixAfterAdd(int z) { while (color[p[z]] == RED) { if (p[z] == left[p[p[z]]]) { int y = right[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == right[p[z]]) { z = p[z]; rotateLeft(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateRight(p[p[z]]); } } else { int y = left[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == left[p[z]]) { z = p[z]; rotateRight(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateLeft(p[p[z]]); } } } color[root] = BLACK; } private void fixAfterRemove(int x) { while (x != root && color[x] == BLACK) { if (x == left[p[x]]) { int w = right[p[x]]; if (color[w] == RED) { color[w] = BLACK; color[p[x]] = RED; rotateLeft(p[x]); w = right[p[x]]; } if (color[left[w]] == BLACK && color[right[w]] == BLACK) { color[w] = RED; x = p[x]; } else { if (color[right[w]] == BLACK) { color[left[w]] = BLACK; color[w] = RED; rotateRight(w); w = right[p[x]]; } color[w] = color[p[x]]; color[p[x]] = BLACK; color[right[w]] = BLACK; rotateLeft(p[x]); x = root; } } else { int w = left[p[x]]; if (color[w] == RED) { color[w] = BLACK; color[p[x]] = RED; rotateRight(p[x]); w = left[p[x]]; } if (color[left[w]] == BLACK && color[right[w]] == BLACK) { color[w] = RED; x = p[x]; } else { if (color[left[w]] == BLACK) { color[right[w]] = BLACK; color[w] = RED; rotateLeft(w); w = left[p[x]]; } color[w] = color[p[x]]; color[p[x]] = BLACK; color[left[w]] = BLACK; rotateRight(p[x]); x = root; } } } color[x] = BLACK; } private void rotateLeft(int x) { int y = right[x]; right[x] = left[y]; if (left[y] != NULL) { p[left[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == left[p[x]]) { left[p[x]] = y; } else { right[p[x]] = y; } } left[y] = x; p[x] = y; } private void rotateRight(int x) { int y = left[x]; left[x] = right[y]; if (right[y] != NULL) { p[right[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == right[p[x]]) { right[p[x]] = y; } else { left[p[x]] = y; } } right[y] = x; p[x] = y; } public void clear() { color[NULL] = BLACK; size = 0; root = NULL; } private void enlarge() { int newLength = Math.max(color.length + 1, (int) (color.length * ENLARGE_SCALE)); key = Arrays.copyOf(key, newLength); left = Arrays.copyOf(left, newLength); right = Arrays.copyOf(right, newLength); p = Arrays.copyOf(p, newLength); color = Arrays.copyOf(color, newLength); } private int firstNode() { int x = root; while (left[x] != NULL) { x = left[x]; } return x; } public int getFirst() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = firstNode(); returnedNull = false; return key[x]; } public int removeFirst() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = firstNode(); returnedNull = false; final int removedElement = key[x]; removeNode(x); return removedElement; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntCustomTreeSet that = (EzIntCustomTreeSet) o; if (size != that.size) { return false; } for (int x = firstNode(), y = that.firstNode(); x != NULL; //noinspection SuspiciousNameCombination x = successorNode(x), y = that.successorNode(y) ) { if (key[x] != that.key[y]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int x = firstNode(); x != NULL; x = successorNode(x)) { hash = (hash ^ PrimitiveHashCalculator.getHash(key[x])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int x = firstNode(); x != NULL; x = successorNode(x)) { if (sb.length() > 1) { sb.append(", "); } sb.append(key[x]); } sb.append(']'); return sb.toString(); } private class EzIntTreeSetIterator implements EzIntIterator { private int x; private EzIntTreeSetIterator() { x = firstNode(); } public boolean hasNext() { return x != NULL; } public int next() { if (x == NULL) { throw new NoSuchElementException("Iterator doesn't have more elements"); } final int result = key[x]; x = successorNode(x); return result; } } } }
Java
["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"]
1 second
["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"]
NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "graphs" ]
6b2dfd5501f81bb3c5f11ca11e4c5520
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
2,600
For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them.
standard output
PASSED
fceb1c14097f0623701c2088b4dee5cc
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); String s = in.nextLine(); s = in.nextLine(); boolean raze = false; // boolean breach = false; if (n%2 == 1){ for (int i = 0; i < s.length(); i += 2) if ((s.charAt(i)-'0')%2==1) raze = true; } if (s.length()%2 == 0) { boolean temp = true; for (int i = 1; i < s.length(); i += 2) if ((s.charAt(i)-'0')%2==0) temp = false; if (temp) raze = true; } // else { // if (s.charAt(0)%2==1) raze = true; // } System.out.println(raze ? "1" : "2"); } in.close(); } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
52c80d6285833c85d53de27c4cd6992d
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class A_671 { static int p=1000000007; public static void main(String[] args) throws Exception{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); FastReader sc=new FastReader(); // long k = sc.nextLong(); int n=sc.nextInt(); while(n-->0) { int l=sc.nextInt(); //int no=sc.nextInt(); //String s=""+no; char ar[]=sc.nextLine().toCharArray(); //System.out.println(Arrays.toString(ar)); int r=0; int b=0; if(l%2==0) { for(int i=1;i<l;i+=2) { if((ar[i]-'0')%2==0) { b=1; break; } } if(b==0) r=1; } else { for(int i=0;i<l;i+=2) { if((ar[i]-'0')%2!=0) { r=1; break; } } if(r==0) b=1; } if(b==1) System.out.println(2); else if(r==1) System.out.println(1); } // out.write(sb.toString()); out.flush(); } /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// 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
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
ea63a2f9940a1ce2b36bf4e69c365f59
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { private static FastScanner fs = new FastScanner(); public static void main(String[] args) { int t = fs.nextInt(); while(t-->0) { int n =fs.nextInt(); String digit = fs.next(); /* 1 Raze wins 2 Breach Wins Suppose length is odd 222 When n is odd A will decide at least one odd When n is even B decide i. atleast one even */ if((n&1)==1) { label: { for (int i = 0; i < digit.length(); i+=2) { int a = (digit.charAt(i) - '0'); if ((a & 1) == 1) { System.out.println(1); break label; } } System.out.println(2); } } else { label: { for (int i = 1; i < digit.length(); i+=2) { int a = (digit.charAt(i) - '0'); if ((a & 1) == 0) { System.out.println(2); break label; } } System.out.println(1); } } } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
6127611f477ff5eeebf85b60b70d3aad
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); String s = sc.nextLine(); int flag=0; if(n==1){ int x = Integer.valueOf(s.charAt(0)+""); if(x%2!=0){ System.out.println(1); } else{ System.out.println(2); } } else if(n%2!=0){ // ood raze decide odd for(int i=0;i<n;i+=2){ int x = Integer.valueOf(s.charAt(i)+""); if(x%2!=0){ flag=1; break; } } if(flag==1){ System.out.println(1); } else{ System.out.println(2); } } else{ for(int i=1;i<n;i+=2){ int x = Integer.valueOf(s.charAt(i)+""); if(x%2==0){ flag=1; break; } } if(flag==1){ System.out.println(2); } else{ System.out.println(1); } } } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
5c3c91f595775b34e6c7672947f97e99
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static ArrayList<Integer> adj[]; // static PrintWriter out = new PrintWriter(System.out); static int[][] notmemo; static int k; static int[] a; static int b[]; static int m; static class Pair implements Comparable<Pair> { int c; int d; public Pair(int b, int l) { c = b; d = l; } @Override public int compareTo(Pair o) { return o.d-this.d; } } static Pair s1[]; static ArrayList<Pair> adjlist[]; // static char c[]; public static long mod = (long) (1e9 + 7); static int V; static long INF = (long) 1E16; static int n; static char c[]; static int d[]; static int z; static Pair p[]; static int R; static int C; static int K; static long grid[][]; static Scanner sc = new Scanner(System.in); static int x[]; static int y[]; static PrintWriter out = new PrintWriter(System.out); public static void main(String args[]) throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); char c[]=new char[n]; c=sc.nextLine().toCharArray(); boolean odd=false; for (int i = 0; i < c.length; i+=2) { int z=c[i]-'0'; if(z%2!=0) { odd=true; } } boolean even=false; for (int i = 1; i < c.length; i+=2) { int z=c[i]-'0'; if(z%2==0) { even=true; } } if(even&&n%2==0||(!odd&&n%2!=0)) { System.out.println(2); } else if(n%2==0) { System.out.println(1); } else { System.out.println(1); } } } static long div4[]; static int s[]; static long dp(int sum) { if(sum==n) return 1; if(sum>n) return 0; if(div4[sum]!=-1) return div4[sum]; long ans=0; for (int i = 0; i < s.length; i++) { if(sum+s[i]>n) break; ans+=(dp(sum+s[i])%998244353); ans%=998244353; } return div4[sum]=ans; } static TreeSet<Integer> ts=new TreeSet(); static HashMap<Integer, Integer> compress(int a[]) { ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } static class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n+1]; } int rsq(int b) //O(log n) { int sum = 0; while(b > 0) { sum += ft[b]; b -= b & -b;} //min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a-1); } void point_update(int k, int val) //O(log n), update = increment { while(k <= n) { ft[k] += val; k += k & -k; } //min? } } static ArrayList<Integer> euler=new ArrayList<>(); static ArrayList<Integer> arr; static int[] total; static TreeMap<Integer,Integer> map1; static int zz; //static int dp(int idx,int left,int state) { //if(idx>=k-((zz-left)*2)||idx+1==n) { // return 0; //} //if(memo[idx][left][state]!=-1) { // return memo[idx][left][state]; //} //int ans=a[idx+1]+dp(idx+1,left,0); //if(left>0&&state==0&&idx>0) { // ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1)); //} //return memo[idx][left][state]=ans; //}21 static HashMap<Integer,Integer> map; static int maxa=0; static int ff=123123; static long[][] memo; static long modmod=998244353; static int dx[]= {1,-1,0,0}; static int dy[]= {0,0,1,-1}; static class BBOOK implements Comparable<BBOOK>{ int t; int alice; int bob; public BBOOK(int x,int y,int z) { t=x; alice=y; bob=z; } @Override public int compareTo(BBOOK o) { return this.t-o.t; } } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static class Edge implements Comparable<Edge> { int node;long cost ; long time; Edge(int a, long b,long c) { node = a; cost = b; time=c; } public int compareTo(Edge e){ return Long.compare(time,e.time); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public int chunion(int i,int j, int x2) { if (isSameSet(i, j)) return 0; numSets--; int x = findSet(i), y = findSet(j); int z=findSet(x2); p[x]=z;; p[y]=z; return x; } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static boolean vis[]; static HashSet<Integer> set = new HashSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long l, long o) { if (o == 0) { return l; } return gcd(o, l % o); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } 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); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } public static int[] readarray(int n) throws IOException { int a[]=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); } return a; } public static long[] readlarray(int n) throws IOException { long a[]=new long[n]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextLong(); } return a; } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
ac876d56a4719d67dc0c3c61852954b2
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import java.util.*; import static java.lang.System.*; /* Shortcut--> Arrays.stream(n).parallel().sum(); string builder fast_output --> */ public class cf_hai1 { static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int test_case = sc.nextInt(); // int test_case=1; for (int j = 0; j < test_case; j++) { int n = sc.nextInt(); String s=sc.next(); solve(n,s); } } private static void solve(int n, String s) { int re=0; int ro=0; int be=0; int bo=0; for (int i=0;i<n;i++){ if(i%2==0) { if (((s.charAt(i)) - '0') % 2 == 0) re++; else ro++; } else{ if (((s.charAt(i)) - '0') % 2 == 0) be++; else bo++; } } if (n%2 == 0){ if(be>0) out.println("2"); else out.println("1"); } else { if(ro>0) out.println("1"); else out.println("2"); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
6c8742eeccfc4a4a948236c3794a9b1d
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.*; import java.util.*; public class d2671 implements Runnable { private boolean console=false; public void solve() { int i; int n=in.ni(); char a[]=in.ns().toCharArray(); int r=0,b=0; for(i=0;i<n;i++) { int v=a[i]-'0'; if(i%2==0&&v%2==0) r++; if(i%2!=0&&v%2!=0) b++; } int ol=(n+1)/2; int el=n/2; if(n%2!=0) { if(ol-r>=1) out.println(1); else out.println(2); } else { if(el-b>=1) out.println(2); else out.println(1); } } @Override public void run() { try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } int t= in.ni(); while (t-->0) { solve(); out.flush(); } } private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new d2671().run(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (!console && System.getProperty("user.name").equals("sachan")) { outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt"); inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } static class FastInput { InputStream obj; public FastInput(InputStream obj) { this.obj = obj; } byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; } String ns() { int b = skip();StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();} int ni() { int num = 0, b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; }b = readByte(); }} long nl() { long num = 0;int b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10L + (b - '0'); } else { return minus ? -num : num; }b = readByte(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; } float nf() {return Float.parseFloat(ns());} double nd() {return Double.parseDouble(ns());} char nc() {return (char) skip();} } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
16c68c0f25999fdf5368c61af02d98cb
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(buffer.readLine()); while (t-- > 0){ int n = Integer.parseInt(buffer.readLine().trim()); String num = buffer.readLine().trim(); int[] arr = new int[n + 1]; for (int pos = 1; pos <= n; pos++) { arr[pos] = Character.getNumericValue(num.charAt(pos-1)); } boolean oddPres = false, evenPres = false; for (int pos = 1; pos <= n; pos++) { if (pos % 2 == 1 && arr[pos] % 2 == 1) oddPres = true; else if (pos % 2 == 0 && arr[pos] % 2 == 0) evenPres = true; } // System.out.println("a"); if (n % 2 == 0) { if (evenPres) sb.append("2"); else sb.append("1"); } else { if (oddPres) sb.append("1"); else sb.append("2"); } sb.append("\n"); } System.out.println(sb); } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
b67631b665d7d77a904cbb0d1c3109b3
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int testCases = sc.nextInt(); for (int t = 0; t < testCases; t++) { int n = sc.nextInt(); sc.nextLine(); String str = sc.nextLine(); char c[] = str.toCharArray(); int razeEven = 0; int razeOdd = 0; int breachOdd = 0; int breachEven = 0; for (int i = 0; i < n; i++) { int cur = c[i] - '0'; if (i % 2 == 0) { if (cur % 2 == 0) { razeEven++; } else { razeOdd++; } } else { if (cur % 2 != 0) { breachOdd++; } else { breachEven++; } } } int ans = -1; if (n == 0) { int cur = c[0] - '0'; if (cur % 2 == 0) { ans = 2; } else { ans = 1; } sb.append(ans).append("\n"); continue; } if (n % 2 == 0) { // In Breach hand if (breachEven == 0) { ans = 1; } else { ans = 2; } } else { if (razeOdd == 0) { ans = 2; } else { ans = 1; } } sb.append(ans).append("\n"); } System.out.print(sb); } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
a23ab5c45a614e6c36a9518de9d713a9
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
//nitin kumar das //sept 24, 2020 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CodeForces extends Functions { public static void main(String[] args) { Scanner sc = new Scanner(); int testCase = sc.nextInt(); while (testCase-- > 0) { int n = sc.nextInt(); String str = sc.next(); char[] ch= str.toCharArray(); int razeMarkEvens = 0; int breachMarkOdds = 0; for(int i=0;i<n;i++){ int i1 = Integer.parseInt(ch[i] + "") % 2; if(i%2==0) { if (i1 == 0) razeMarkEvens++; } else{ if (i1 == 1)breachMarkOdds++; } } if(n%2==1){ if(n/2+1==razeMarkEvens) System.out.println(2); else System.out.println(1); } else{ if(n/2==breachMarkOdds) System.out.println(1); else System.out.println(2); } } } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while (!st.hasMoreTokens()) 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 int[] setIntegerArray(int n){ int[] arr =new int[n]; for(int i=0;i<n;i++)arr[i] = nextInt(); return arr; } public long[] setLongArray(int n){ long[] arr =new long[n]; for(int i=0;i<n;i++)arr[i] = nextLong(); return arr; } } class Functions { public static int mod = (int)1e9+7; public static void sort(int[] a){ ArrayList<Integer> temp = new ArrayList<>(); for (int j : a) temp.add(j); Collections.sort(temp);; for(int i=0;i<a.length;i++)a[i] = temp.get(i); } public static long factorial(int n){ long fact = 1L; for(int i=2;i<=n;i++)fact= (fact*i)%mod; return fact; } public static void sortRev(int[] a){ sort(a); int left = 0; int right = a.length-1; while (left<right){ int temp =a[left]; a[left] = a[right]; a[right] = temp; left++; right--; } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
b2a6015a7cb45001325da36772a3997d
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CodeForces extends Functions { public static void main(String[] args) { Scanner sc = new Scanner(); int testCase = sc.nextInt(); while (testCase-- > 0) { int n = sc.nextInt(); String[] str = sc.next().split(""); boolean[] isMarked = new boolean[n]; while (n>1){ int x = -1; for(int i=0;i<n;i+=2){ if(isMarked[i])continue; if(Integer.parseInt(str[i])%2==0){ x=i; break; } } if(x==-1){ for(int i=0;i<n;i+=2){ if(isMarked[i])continue; x=i; break; } } isMarked[x]=true; int count = 0; for(int i=0;i<n;i++)if(!isMarked[i])count++; if(count==1)break; x=-1; for(int i=1;i<n;i+=2){ if(isMarked[i])continue;; if(Integer.parseInt(str[i])%2==1){ x=i; break; } } if(x==-1){ for(int i=1;i<n;i+=2){ if(isMarked[i])continue;; x=i; break; } } isMarked[x]=true; count = 0; for(int i=0;i<n;i++)if(!isMarked[i])count++; if(count==1)break; } for(int i=0;i<n;i++){ if(!isMarked[i]){ if(Integer.parseInt(str[i])%2==0) System.out.println(2); else System.out.println(1); break; } } } } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while (!st.hasMoreTokens()) 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 int[] setIntegerArray(int n){ int[] arr =new int[n]; for(int i=0;i<n;i++)arr[i] = nextInt(); return arr; } public long[] setLongArray(int n){ long[] arr =new long[n]; for(int i=0;i<n;i++)arr[i] = nextLong(); return arr; } } class Functions { public static int mod = (int)1e9+7; public static void sort(int[] a){ ArrayList<Integer> temp = new ArrayList<>(); for (int j : a) temp.add(j); Collections.sort(temp);; for(int i=0;i<a.length;i++)a[i] = temp.get(i); } public static long factorial(int n){ long fact = 1L; for(int i=2;i<=n;i++)fact= (fact*i)%mod; return fact; } public static void sortRev(int[] a){ sort(a); int left = 0; int right = a.length-1; while (left<right){ int temp =a[left]; a[left] = a[right]; a[right] = temp; left++; right--; } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
09e4e71680e06699bbe6cdd094fdb03f
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.*; import java.util.*; public class A { static int n; static int[] arr; static char[] s; public static void main(String[] args) throws IOException { Flash f = new Flash(); int T = f.ni(); for(int tc = 1; tc <= T; tc++){ n = f.ni(); String str = new String(" "); str += f.nextLine(); s = str.toCharArray(); System.out.println(fn()); } } static int fn() { if((n&1) == 0){ boolean even = false; for(int i = 1; i <= n; i++){ if((i&1) == 0){ int num = s[i]-'0'; if((num&1) == 0){ even = true; break; } } } return even ? 2 : 1; } else{ boolean odd = false; for(int i = 1; i <= n; i++){ if((i&1) == 1){ int num = s[i]-'0'; if((num&1) == 1){ odd = true; break; } } } return odd ? 1 : 2; } } static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static int swap(int itself, int dummy) { return itself; } //SecondThread static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } //nextInt() int ni(){ return Integer.parseInt(next()); } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } //nextLong() long nl(){ return Long.parseLong(next()); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
cee98d5d809db70a1dfa8cdfb6aede19
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.*; import java.util.*; public class A { static int n; static int[] arr; static char[] s; public static void main(String[] args) throws IOException { Flash f = new Flash(); int T = f.ni(); for(int tc = 1; tc <= T; tc++){ n = f.ni(); String str = new String(" "); str += f.nextLine(); s = str.toCharArray(); System.out.println(fn()); } } static int fn() { List<Integer> me = new ArrayList<>(); List<Integer> other = new ArrayList<>(); for(int i = 1; i <= n; i++){ if((i&1) == 1) me.add(s[i]-'0'); else other.add(s[i]-'0'); } boolean f = true; int ans = -1; while(true){ if(me.isEmpty()){ ans = other.get(0); break; } else if(other.isEmpty()){ ans = me.get(0); break; } if(f){ boolean ok = false; for(int i = 0; i < me.size(); i++){ if(me.get(i) % 2 == 0){ ok = true; me.remove(i); break; } } if(!ok && !me.isEmpty()) me.remove(0); } else{ boolean ok = false; for(int i = 0; i < other.size(); i++){ if(other.get(i) % 2 == 1){ ok = true; other.remove(i); break; } } if(!ok && !other.isEmpty()) other.remove(0); } f = !f; } if(ans % 2 == 0) return 2; else return 1; } static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static int swap(int itself, int dummy) { return itself; } //SecondThread static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } //nextInt() int ni(){ return Integer.parseInt(next()); } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } //nextLong() long nl(){ return Long.parseLong(next()); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
30ca942f5adec9fd97c2faa685341e68
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.Scanner; public class raze { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t= sc.nextInt(); while(t-->0){ int n = sc.nextInt(); String s=sc.next(); int[] a= new int[n]; for(int i=0;i<n;i++){ a[i]=Integer.parseInt(String.valueOf(s.charAt(i))); } System.out.println(find(a,n)); } } static int find(int[] a,int n){ if(n==1){ if(a[0]%2==0)return 2; else return 1; } if(n%2==0){ for(int i=1;i<n;i+=2) { if(a[i]%2==0)return 2; } return 1; } else{ for(int i=0;i<n;i+=2) { if(a[i]%2!=0)return 1; } return 2; } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
d4fb903a9a53d24382d4f6376de8cf93
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; public class digitGame { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); for(int t = 0;t<T;t++){ long n = sc.nextLong(); sc.nextLine(); String str = sc.nextLine(); int eposeven = 0; int eposodd = 0; int oposeven = 0; int oposodd = 0; for(int i = 0;i<n;i++){ int x = str.charAt(i) - '0'; if((i+1)%2 != 0){ if(x % 2 == 0){ oposeven++; } else{ oposodd++; } } else{ if(x % 2 == 0){ eposeven++; } else{ eposodd++; } } } if(n%2 == 0){ if(eposeven == 0){ System.out.println(1); } else{ System.out.println(2); } } else{ if(oposodd == 0){ System.out.println(2); } else{ System.out.println(1); } } } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
262c90df10824359d7126c8e33539362
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.Scanner; public class solution { public static void main(String args[]) { Scanner sc=new Scanner(System.in); long t=sc.nextLong(); while(t-->0) { int n=sc.nextInt(); String a=sc.next(); char[] c=new char[n]; c=a.toCharArray(); if(n%2!=0) { int flag=0; for(int i=0;i<n;i=i+2) { int x=Integer.parseInt(String.valueOf(c[i])); if(x%2!=0) { flag=1; break; } } if(flag==1) { System.out.println("1"); } else { System.out.println("2"); } } else { int flag=0; for(int i=1;i<n;i=i+2) { int x=Integer.parseInt(String.valueOf(c[i])); if(x%2==0) { flag=1; break; } } if(flag==1) { System.out.println("2"); } else { System.out.println("1"); } } } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
e11129ae36e400a464176c313a23ce94
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class digit { 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 s=new FastReader(); int t = s.nextInt(); while(t-->0){ int n = s.nextInt(); String s1 = s.nextLine(); String[] tk = s1.split(""); int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = Integer.parseInt(tk[i]); int e1=0,e2=0,o1=0,o2=0; byte ans; for(int i=0; i<n; i+=2){ if(a[i]%2==0) e1++; else o1++; } for(int i=1; i<n; i+=2){ if(a[i]%2!=0) o2++; else e2++; } if (n%2==0){ if (e2>0) ans =2; else ans =1; } else{ if (o1>0) ans =1; else ans =2; } System.out.println(ans); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
72fa4e66b7754ba250cfb74273920301
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class DigitGame { 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; } } 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; } int[] readArray(int n, int size) { int[] a = new int[size]; for (int i = 0; i < n; i++) { a[i] = this.nextInt(); } return a; } long[] readLongArray(int n, int size) { long[] a = new long[size]; for (int i = 0; i < n; i++) { a[i] = this.nextLong(); } return a; } } static void ruffleSort(long[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n); long temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static final Random random = new Random(); static void ruffleSort(int[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } public static void main(String[] args) { FastReader fs = new FastReader(); int t = fs.nextInt(); for (int z = 0; z < t; z++) { int n = fs.nextInt(); char[] a = fs.next().toCharArray(); boolean oddDigit = false; boolean evenDigit = false; for(int i = 0; i < a.length; i++) { if(i % 2 == 0 && (a[i] - '0') % 2 == 1) oddDigit = true; else if(i % 2 == 1 && (a[i] - '0') % 2 == 0) { evenDigit = true; } } if(n % 2 == 0) { if(evenDigit) System.out.println(2); else System.out.println(1); } else { if(oddDigit) System.out.println(1); else System.out.println(2); } } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
c87401bde5aa2f0b4633a4754ff2ef0b
train_002.jsonl
1600526100
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static void main (String[] args) { // your code goes here Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int i=0; i<t; i++) { int n = s.nextInt(); String x = s.next(); int j = 0; int f = 0; while(j<n) { int d = Integer.parseInt(String.valueOf(x.charAt(j))); // System.out.println(d); if(j%2==0) { if(n%2==1 && d%2==1) { f = 1; break; } else f = 2; } else { if(n%2==0 && d%2==0) { f = 2; break; } else f = 1; } j++; } System.out.println(f); } } }
Java
["4\n1\n2\n1\n3\n3\n102\n4\n2069"]
1 second
["2\n1\n1\n2"]
NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.
Java 11
standard input
[ "implementation", "greedy", "games" ]
c9225c915669e183cbd8c20b848d96e5
First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$ Β β€” the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.
900
For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.
standard output
PASSED
ebdcad01f341418710f9aadf74f9d004
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.round; import static java.lang.Math.sqrt; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverse; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; import static java.util.Comparator.comparing; import static java.util.Comparator.comparingInt; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; class Pair { long l, r; Pair(long l, long r) { this.l = l; this.r = r; } } private void solve() throws IOException { int n = in.nextInt(); long x = in.nextLong(), y = in.nextLong(); Pair[] p = new Pair[n]; for (int i = 0; i < n; i++) p[i] = new Pair(in.nextLong(), in.nextLong()); sort(p, comparingLong(o -> o.l)); long mod = (long) 1e9 + 7, ans = 0; TreeMap<Long, Integer> multiset = new TreeMap<>(); for (int i = 0; i < n; i++) { if (multiset.lowerKey(p[i].l) != null && x > y * (p[i].l - multiset.lowerKey(p[i].l))) { long cur = multiset.lowerKey(p[i].l); ans += y * (p[i].r - cur) % mod; multiset.put(cur, multiset.get(cur) - 1); if (multiset.get(cur) == 0) multiset.remove(cur); } else ans += x + y * (p[i].r - p[i].l) % mod; ans %= mod; multiset.put(p[i].r, multiset.getOrDefault(p[i].r, 0) + 1); } out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } 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 { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
674640cd2e678f633e1befb0e0648583
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { int n = input.nextInt(), x = input.nextInt(), y = input.nextInt(); int rent = x - y; int costPerMinute = y; class Event { final int time; final boolean programStart; Event(int time, boolean programStart) { this.time = time; this.programStart = programStart; } } Event[] events = new Event[2 * n]; long answer = 0; int mod = 1_000_000_007; for (int i = 0; i < n; i++) { int startTime = input.nextInt(); events[2 * i] = new Event(startTime, true); int endTime = input.nextInt() + 1; events[2 * i + 1] = new Event(endTime, false); answer += (long)(endTime - startTime) * costPerMinute; answer %= mod; } Arrays.sort(events, Comparator.comparingInt((Event e) -> e.time) .thenComparing((e1, e2) -> Boolean.compare(e1.programStart, e2.programStart))); int[] tvs = new int[n]; int tvi = 0; for (Event event : events) { if (!event.programStart) { tvs[tvi++] = event.time; } else { if (tvi > 0) { long keepCost = (long) (event.time - tvs[tvi - 1]) * costPerMinute; if (keepCost <= rent) { tvi--; answer += keepCost; } else { tvi = 0; answer += rent; } } else { answer += rent; } } } answer %= mod; writer.println(answer); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
086318ac056fe0174782a18c50f275cf
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; public class Main { static long MOD = 1000000007; static void D(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long x = sc.nextLong(); long y = sc.nextLong(); List<Pair> inpList = new ArrayList<>(); for(int i = 0; i<n; ++i){ long st = sc.nextLong(); long ed = sc.nextLong(); Pair p = new Pair(st,ed); inpList.add(p); } Collections.sort(inpList); // TreeSet<Long> tvSet = new TreeSet<>(); PriorityQueue<Long> queue = new PriorityQueue<>(new Comparator<Long>() { public int compare(Long l1, Long l2) { if(l1 < l2) return -1; if(l1 > l2) return 1; return 0; } }); Stack<Long> stack = new Stack<>(); long totalCost = 0; for(int i = 0; i<n; ++i){ Pair curShow = inpList.get(i); long r = curShow.sec; long l = curShow.fir; while (queue.size()!=0 && queue.peek() < l) { stack.add(queue.poll()); } // Long nearestTv = tvSet.floor(l - 1); if (stack.size() == 0) { // no tv available, add new tv totalCost = (totalCost + x) % MOD; } else { // determine whether it's more worth continuing or making a new tv long oldCost = y * (curShow.fir - stack.peek()); if (oldCost > x) { totalCost = (totalCost + x) % MOD; } else { totalCost = (totalCost + oldCost) % MOD; stack.pop(); } } // tvSet.add(r); queue.add(r); totalCost += (r - l) * y; totalCost %= MOD; } System.out.println(totalCost); } static class Pair implements Comparable<Pair> { long fir; long sec; Pair(long a, long b){ this.fir = a; this.sec = b; } @Override public int compareTo(Pair o) { if (this.fir > o.fir) return 1; else if (this.fir == o.fir) { if (this.sec > o.sec) return 1; else if (this.sec == o.sec) return 0; } return -1; } } public static void main(String[] args) { D(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
5c080f3b28c4b19b4949aabc2c7721af
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static Reader scan; static PrintWriter pw; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); int n = ni(),x = ni(), y = ni(); int lim = (x/y); long MOD = 1_000_000_007; Show arr[] = new Show[n]; TreeSet<Show> ts = new TreeSet<>(new Comparator1()); for(int i=0;i<n;++i) { arr[i] = new Show(ni(), ni(), i); } Arrays.sort(arr); long ans = 0; for(int i=0;i<n;++i) { Show prev = ts.lower(new Show(45, arr[i].start-1, 100000001)); if(prev==null || arr[i].start - prev.end > lim) { ans+=x+1L*y*(arr[i].end - arr[i].start); } else { ans+=1L*y*(arr[i].end - prev.end); ts.remove(prev); } ans%=MOD; ts.add(arr[i]); } pl(ans); pw.flush(); pw.close(); } static class Show implements Comparable<Show> { int start, end, index; public Show(int start, int end, int index) { this.start = start; this.end = end; this.index = index; } public int compareTo(Show other) { return this.start - other.start; } public String toString() { return "{"+start+","+end+","+index+"}"; } } static class Comparator1 implements Comparator<Show> { public int compare(Show a, Show b) { if(a.end!=b.end) { return a.end - b.end; } return a.index - b.index; } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; 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
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
34bda82ef36f3dc7688a98b20e47fbba
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int mod = (int) (1e9 + 7); public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long x = in.nextInt(); long y = in.nextInt(); List<poi> pois = new ArrayList<>(); for (int i = 0; i < n; i++) { int st = in.nextInt(); int en = in.nextInt(); pois.add(new poi(st, 0)); pois.add(new poi(en + 1, 1)); } pois.sort((p1, p2) -> { if (p1.x == p2.x) { return p2.iss - p1.iss; } else { return p1.x - p2.x; } }); ArrayDeque<Integer> dq = new ArrayDeque<>(); long ans = 0; int lp = -1; long rs = 0; for (int i = 0; i < pois.size(); i++) { poi cp = pois.get(i); if (cp.iss == 0) { if (lp != -1 && lp < cp.x + 1) { ans += ((rs * (cp.x + 1 - lp)) % mod) * y; ans %= mod; } rs++; if (dq.isEmpty()) { ans += x; ans %= mod; } else { int le = dq.removeLast(); if ((cp.x - le) * y < x - y) { ans += (cp.x - le) * y; ans %= mod; ans += y; ans %= mod; } else { dq.clear(); ans += x; ans %= mod; } } lp = cp.x + 1; } else { if (lp != -1 && lp < cp.x) { ans += ((rs * (cp.x - lp)) % mod) * y; ans %= mod; } rs--; dq.addLast(cp.x); lp = cp.x; } } out.print(ans); } class poi { int x; int iss; public poi(int x, int iss) { this.x = x; this.iss = iss; } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(long i) { writer.print(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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
d73a6f485f0fb790ab89bebca221cd75
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN void solve(int TC) throws Exception{ int n = ni(); long x = nl(), y = nl(); long[][] a= new long[n][]; for(int i = 0; i< n; i++)a[i] = new long[]{nl(), nl()}; Arrays.sort(a, (long[] l1, long[] l2) -> { if(l1[0]==l2[0])return Long.compare(l1[1], l2[1]); return Long.compare(l1[0], l2[0]); }); long ans = 0; MyTreeSet<Long> avail = new MyTreeSet<>(), inuse = new MyTreeSet<>(); for(int i = 0; i< n; i++){ while(!inuse.isEmpty()){ long f = inuse.first(); if(f>=a[i][0])break; avail.add(f); inuse.remove(f); } long a1 = (avail.isEmpty())?IINF:(y*(a[i][0]-avail.last())); if(x>=a1){ ans = add(ans,add(a1,mul(a[i][1]-a[i][0], y))); avail.remove(avail.last()); }else{ ans = add(ans,add(x,mul(a[i][1]-a[i][0],y))); } inuse.add(a[i][1]); } pn(ans); } long mul(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long add(long a, long b){ if(Math.abs(a)>=mod)a%=mod; if(a<0)a+=mod; if(Math.abs(b)>=mod)b%=mod; if(b<0)b+=mod; a+=b; if(Math.abs(a)>=mod)a%=mod; return a; } class MyTreeSet<T>{ private int size; private TreeMap<T, Integer> map; public MyTreeSet(){ size = 0; map = new TreeMap<>(); } public int size(){return size;} public boolean isEmpty(){return size==0;} public void add(T t){ size++; map.put(t, map.getOrDefault(t, 0)+1); } public boolean remove(T t){ if(!map.containsKey(t))return false; size--; int c = map.get(t); if(c==1)map.remove(t); else map.put(t, c-1); return true; } public boolean contains(T t){return map.getOrDefault(t,0)>0;} public T ceiling(T t){return map.ceilingKey(t);} public T floor(T t){return map.floorKey(t);} public T first(){return map.firstKey();} public T last(){return map.lastKey();} } //SOLUTION END long mod = (long)1e9+7, IINF = (long)1e17; final int MAX = (int)1e5+1, INF = (int)2e9, root = 3; DecimalFormat df = new DecimalFormat("0.000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh for(int i = 1; i<= T; i++)solve(i); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
66e8e1f66aa9989eab9018ff96febf76
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long x = sc.nextLong(); long y = sc.nextLong(); Show show[] = new Show[n]; for(int i = 0; i < n; ++i) show[i] = new Show(sc.nextLong(), sc.nextLong()); Arrays.sort(show, new Comparator<Show>() { public int compare(Show s1, Show s2) { if(s1.l > s2.l) return 1; if(s1.l < s2.l) return -1; return 0; } }); PriorityQueue<Long> queue = new PriorityQueue<>(new Comparator<Long>() { public int compare(Long l1, Long l2) { if(l1 < l2) return -1; if(l1 > l2) return 1; return 0; } }); long ans = 0; Stack<Long> stack = new Stack<>(); for(int i = 0; i < n; ++i) { long l = show[i].l; long r = show[i].r; while(queue.size() != 0 && queue.peek() < l) stack.push(queue.poll()); if(stack.size() == 0) { ans += x + (r - l) * y; ans %= 1000000007; } else { if((l - stack.peek()) * y < x) { ans += (r - stack.pop()) * y; ans %= 1000000007; } else { ans += x + (r - l) * y; ans %= 1000000007; } } queue.add(r); } System.out.print(ans); } } class Show { long l, r; Show(long a, long b) { l = a; r = b; } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
825847e6fc298f8808304de5f56c5963
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
//package round523; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.PriorityQueue; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); long X = ni(), Y = ni(); int mod = 1000000007; int[][] rs = new int[n][]; for(int i = 0;i < n;i++){ rs[i] = na(2); } Arrays.sort(rs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); PriorityQueue<Integer> mlast = new PriorityQueue<>(); PriorityQueue<Integer> wait = new PriorityQueue<>(); long cost = 0; for(int[] r : rs){ while(!wait.isEmpty() && wait.peek() < r[0]){ mlast.add(-wait.poll()); } while(!mlast.isEmpty() && (r[0]+mlast.peek())*Y >= X){ mlast.poll(); } if(mlast.isEmpty()){ cost += X + (r[1]-r[0])*Y; cost %= mod; }else{ cost += (r[1]+mlast.poll())*Y; cost %= mod; } wait.add(r[1]); } out.println(cost); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
58fe5e9e4e6b26f5cb5308e746c229df
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ public class cf4 implements Runnable{ static class pair { int i; long w; pair(int i, long w) { this.i = i; this.w = w; } } static class comp implements Comparator<pair> { public int compare(pair x, pair y) { if(x.w > y.w) return -1; if(x.w < y.w) return 1; return 0; } } static void addMap(TreeMap<Integer, ArrayList<Integer>> hm, int x, int i) { if(hm.get(x) == null) hm.put(x, new ArrayList<Integer>()); hm.get(x).add(i); } static void subMap(TreeMap<Integer, ArrayList<Integer>> hm, int x, int i) { if(hm.get(x) == null) hm.put(x, new ArrayList<Integer>()); hm.get(x).add(-i); } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); long x = s.nextLong(), y = s.nextLong(); PriorityQueue<pair> pq = new PriorityQueue<pair>(new comp()); TreeMap<Integer, ArrayList<Integer>> hm = new TreeMap<Integer, ArrayList<Integer>>(); int[] l = new int[n + 1]; for(int i = 1; i <= n; i++) { l[i] = s.nextInt(); int r = s.nextInt(); addMap(hm, l[i], i); subMap(hm, r + 1, i); } long mod = (long)1e9 + 7; long totalCost = 0; int[] vis = new int[n + 1]; int[] val = new int[n + 1]; long[] cost = new long[n + 1]; for(Map.Entry<Integer, ArrayList<Integer>> e : hm.entrySet()) { int pos = e.getKey(); ArrayList<Integer> temp = e.getValue(); for(int i = 0; i < temp.size(); i++) { if(temp.get(i) < 0) { pq.add(new pair(val[-temp.get(i)], pos - 1)); vis[val[-temp.get(i)]] = 0; cost[-temp.get(i)] = (cost[-temp.get(i)] + (pos - l[-temp.get(i)] - 1) * y % mod) % mod; } } for(int i = 0; i < temp.size(); i++) { if(temp.get(i) < 0) continue; while(!pq.isEmpty() && vis[val[pq.peek().i]] == 1) pq.poll(); if(pq.isEmpty() || y * (pos - pq.peek().w) >= x) { vis[temp.get(i)] = 1; val[temp.get(i)] = temp.get(i); cost[temp.get(i)] = (cost[temp.get(i)] + x) % mod; } else { vis[pq.peek().i] = 1; val[temp.get(i)] = pq.peek().i; cost[temp.get(i)] = (cost[temp.get(i)] + y * (pos - pq.peek().w) % mod) % mod; } } } for(int i = 1; i <= n; i++) totalCost = (cost[i] + totalCost) % mod; w.println(totalCost); w.close(); } 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 cf4(),"cf4",1<<26).start(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
ddd1a7b0d1a91fa1552bded830a99484
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ public class cf4 implements Runnable{ static class pair { int i; long w; pair(int i, long w) { this.i = i; this.w = w; } } static class comp implements Comparator<pair> { public int compare(pair x, pair y) { if(x.w > y.w) return -1; if(x.w < y.w) return 1; return 0; } } static void addMap(TreeMap<Integer, ArrayList<Integer>> hm, int x, int i) { if(hm.get(x) == null) hm.put(x, new ArrayList<Integer>()); hm.get(x).add(i); } static void subMap(TreeMap<Integer, ArrayList<Integer>> hm, int x, int i) { if(hm.get(x) == null) hm.put(x, new ArrayList<Integer>()); hm.get(x).add(-i); } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); long x = s.nextLong(), y = s.nextLong(); PriorityQueue<pair> pq = new PriorityQueue<pair>(new comp()); TreeMap<Integer, ArrayList<Integer>> hm = new TreeMap<Integer, ArrayList<Integer>>(); int[] l = new int[n + 1]; for(int i = 1; i <= n; i++) { l[i] = s.nextInt(); int r = s.nextInt(); addMap(hm, l[i], i); subMap(hm, r + 1, i); } long mod = (long)1e9 + 7; long totalCost = 0; int[] vis = new int[n + 1]; int[] val = new int[n + 1]; long[] cost = new long[n + 1]; for(Map.Entry<Integer, ArrayList<Integer>> e : hm.entrySet()) { int pos = e.getKey(); ArrayList<Integer> temp = e.getValue(); for(int i = 0; i < temp.size(); i++) { if(temp.get(i) < 0) { pq.add(new pair(-temp.get(i), pos - 1)); vis[val[-temp.get(i)]] = 0; cost[-temp.get(i)] = (cost[-temp.get(i)] + (pos - l[-temp.get(i)] - 1) * y % mod) % mod; } } for(int i = 0; i < temp.size(); i++) { if(temp.get(i) < 0) continue; while(!pq.isEmpty() && vis[val[pq.peek().i]] == 1) pq.poll(); if(pq.isEmpty() || y * (pos - pq.peek().w) >= x) { vis[temp.get(i)] = 1; val[temp.get(i)] = temp.get(i); cost[temp.get(i)] = (cost[temp.get(i)] + x) % mod; } else { vis[val[pq.peek().i]] = 1; val[temp.get(i)] = val[pq.peek().i]; cost[temp.get(i)] = (cost[temp.get(i)] + y * (pos - pq.peek().w) % mod) % mod; } } } for(int i = 1; i <= n; i++) totalCost = (cost[i] + totalCost) % mod; w.println(totalCost); w.close(); } 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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 cf4(),"cf4",1<<26).start(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
5e083b1f9296ccdc5a371681d535dd5c
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class D { public static void main(String[] args) { Scanner input = new Scanner(); StringBuilder output = new StringBuilder(); int n = input.nextInt(); long x = input.nextInt(); long y = input.nextInt(); ArrayList<Event> e = new ArrayList<Event>(2*n); for (int i = 0; i < n; i++) { int a = input.nextInt(); int b = input.nextInt(); e.add(new Event(a, true, b)); e.add(new Event(b, false, a)); } Collections.sort(e); int count = 0; final int MOD = 1000000007; ArrayDeque<Integer> ends = new ArrayDeque<>(); long cost = 0; for (Event f : e) { if (f.start) { if ( !ends.isEmpty() && f.t > ends.peek() && (long)(f.t - ends.peek()) * y < x ) { // System.err.println(f.t + " " + ends); cost += (long)(f.t - ends.peek()) * y; cost %= MOD; ends.pop(); } else { cost += x; cost %= MOD; } } else { count--; ends.push(f.t); cost += (long)(f.t - f.e) * y; cost %= MOD; } } System.out.println(cost); } static class Event implements Comparable<Event> { int t; int e; boolean start; Event(int tt, boolean ss, int ee) { t = tt; start = ss; e = ee; } public int compareTo(Event e) { if (t == e.t) { if (start == e.start) return 0; if (start) return -1; return 1; } return Integer.compare(t, e.t); } } private static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(Reader in) { br = new BufferedReader(in); } public Scanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } // end Scanner }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
3b84c609a59287ecc94a7d6ca23e0d10
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class TVShows { private static final int MOD = 1000000007; public static void solve(FastIO io) { int N = io.nextInt(); long X = io.nextLong(); long Y = io.nextLong(); Range[] ranges = new Range[N]; for (int i = 0; i < N; ++i) { long L = io.nextLong(); long R = io.nextLong(); ranges[i] = new Range(L, R); } Arrays.sort(ranges, Range.BY_L); // PriorityQueue<Long> pq = new PriorityQueue(); CountMap cm = new CountMap(); long cost = 0; for (int i = 0; i < N; ++i) { Long before = cm.lowerKey(ranges[i].L); if (before == null || Y * (ranges[i].L - before) >= X) { cost += X + (Y * (ranges[i].R - ranges[i].L)); } else { cost += Y * (ranges[i].R - before); cm.decrement(before); } cm.increment(ranges[i].R); cost %= MOD; // while (!pq.isEmpty() && pq.peek() < ranges[i].L && Y * (ranges[i].L - pq.peek() - 1) >= X) { // pq.poll(); // } // if (pq.isEmpty() || pq.peek() >= ranges[i].L) { // cost += X + (Y * (ranges[i].R - ranges[i].L)); // System.out.format("i = %d, used new TV\n", i); // } else { // long end = pq.poll(); // cost += Y * (ranges[i].R - end); // System.out.format("i = %d, used old prev = %d\n", i, end); // } // cost %= MOD; // pq.offer(ranges[i].R); // System.out.format("i = %d [%d, %d], cost = %d, pq = %s\n", i, ranges[i].L, ranges[i].R, cost, pq); } io.println(cost); } private static class CountMap extends TreeMap<Long, Integer> { public int getCount(long k) { return getOrDefault(k, 0); } public void increment(long k) { put(k, getCount(k) + 1); } public void decrement(long k) { int v = getCount(k) - 1; if (v == 0) { remove(k); } else { put(k, v); } } } private static class Range { public long L, R; public Range(long lo, long hi) { this.L = lo; this.R = hi; } public static final Comparator<Range> BY_L = new Comparator<Range>() { @Override public int compare(Range lhs, Range rhs) { return Long.compare(lhs.L, rhs.L); } }; } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
c92d2f870693db3591cb278dac188eac
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class TVShows { private static final int MOD = 1000000007; public static void solve(FastIO io) { int N = io.nextInt(); long X = io.nextLong(); long Y = io.nextLong(); Range[] ranges = new Range[N]; for (int i = 0; i < N; ++i) { long L = io.nextLong(); long R = io.nextLong(); ranges[i] = new Range(L, R); } Arrays.sort(ranges, Range.BY_L); CountMap cm = new CountMap(); long cost = 0; for (int i = 0; i < N; ++i) { Long before = cm.lowerKey(ranges[i].L); if (before == null || Y * (ranges[i].L - before) >= X) { cost += X + (Y * (ranges[i].R - ranges[i].L)); } else { cost += Y * (ranges[i].R - before); cm.decrement(before); } cm.increment(ranges[i].R); cost %= MOD; } io.println(cost); } private static class CountMap extends TreeMap<Long, Integer> { public int getCount(long k) { return getOrDefault(k, 0); } public void increment(long k) { put(k, getCount(k) + 1); } public void decrement(long k) { int v = getCount(k) - 1; if (v == 0) { remove(k); } else { put(k, v); } } } private static class Range { public long L, R; public Range(long lo, long hi) { this.L = lo; this.R = hi; } public static final Comparator<Range> BY_L = new Comparator<Range>() { @Override public int compare(Range lhs, Range rhs) { return Long.compare(lhs.L, rhs.L); } }; } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
0fb736f6a5bf79ff54d2b6c319ace7cf
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class D { static long MOD = 1000000007L; public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); long X = Long.parseLong(st.nextToken()); long Y = Long.parseLong(st.nextToken()); Range[] arr = new Range[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); arr[i] = new Range(a,b); } Arrays.sort(arr); TreeMap<Integer, Integer> active = new TreeMap<Integer, Integer>(); long res = 0L; for(Range r: arr) { if(active.size() == 0) { res += X+Y*(long)(r.b-r.a); res %= MOD; push(active, r.b);//active.add(r.b); } else { //find earliest tv to use/remove if(active.firstKey() >= r.a) { res += X+Y*(long)(r.b-r.a); res %= MOD; push(active, r.b); } else { int removed = active.floorKey(r.a-1); long timeDif = r.a-removed; /* res += Math.min(Y*timeDif, X); res %= MOD; res += Y*(long)(r.b-r.a); if(Y*timeDif > X) pull(active, removed);//active.remove(active.first()); push(active, r.b); */ if(Y*timeDif >= X) { res += X+Y*(long)(r.b-r.a); res %= MOD; push(active, r.b); } else { res += Y*(long)(r.b-removed); res %= MOD; pull(active, removed); push(active, r.b); } } } } System.out.println(res); } public static void push(TreeMap<Integer, Integer> map, int k) { if(!map.containsKey(k)) map.put(k,0); map.put(k,map.get(k)+1); } public static void pull(TreeMap<Integer, Integer> map, int k) { map.put(k,map.get(k)-1); if(map.get(k) == 0) map.remove(k); } } class Range implements Comparable<Range> { public int a; public int b; public Range(int x, int y) { a = x; b = y; } public int compareTo(Range oth) { if(a == oth.a) return b-oth.b; return a-oth.a; } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
0b5cbf3cf4b2f1ee2fea249f5e802ce8
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int[] nxy = ril(3); int n = nxy[0]; int x = nxy[1]; int y = nxy[2]; int[][] intervals = new int[n][]; for (int i = 0; i < n; i++) intervals[i] = ril(2); Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0])); long ans = 0; TreeMap<Integer, Integer> finish = new TreeMap<>(); for (int[] e : intervals) { int s = e[0]; int f = e[1]; // Either grab a TV that finished as recently as possible or grab a new TV long opt1 = Long.MAX_VALUE; long opt2 = Long.MAX_VALUE; Integer tv = finish.lowerKey(s); if (tv != null) { opt1 = ((long) s - tv) * y; } opt2 = x; if (opt1 <= opt2) { ans += opt1; if (finish.get(tv) == 1) finish.remove(tv); else finish.put(tv, finish.get(tv) - 1); finish.put(f, finish.getOrDefault(f, 0) + 1); } else { ans += opt2; finish.put(f, finish.getOrDefault(f, 0) + 1); } ans = (ans + (long) (f - s) * y) % MOD; } pw.println(ans); // Set<Integer> set = new HashSet<>(); // for (int[] e : intervals) { // set.add(e[0]); // set.add(e[1]); // } // List<Integer> cToO = new ArrayList<>(set); // Collections.sort(cToO); // Map<Integer, Integer> oToC = new HashMap<>(); // for (int i = 0; i < cToO.size(); i++) oToC.put(cToO.get(i), i); // int[] begin = new int[cToO.size()]; // int[] end = new int[cToO.size()]; // for (int[] e : intervals) { // begin[oToC.get(e[0])]++; // } } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
605c77cdfe3a7d3f976a672a1e3bf071
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DTVShows solver = new DTVShows(); solver.solve(1, in, out); out.close(); } static class DTVShows { public void solve(int testNumber, ScanReader in, PrintWriter out) { long mod = 1000000007; int n = in.scanInt(); long x = in.scanLong(); long y = in.scanLong(); int[][] ar = new int[n][2]; lr[] pp = new lr[n * 2]; for (int i = 0; i < n; i++) { ar[i][0] = in.scanInt(); ar[i][1] = in.scanInt(); pp[i * 2] = new lr(ar[i][0], 0, i); pp[i * 2 + 1] = new lr(ar[i][1], 1, i); } Arrays.sort(pp); long ans = 0; BSTCustom<Long> bs = new BSTCustom<Long>(true); for (int i = 0; i < 2 * n; i++) { if (pp[i].type == 0) { long low = 0; long high = bs.size() - 1; long index = bs.size(); while (low <= high) { long mid = (low + high) / 2; long val = bs.get(mid); if (val > pp[i].lr) { high = mid - 1; } else { if ((pp[i].lr - val + 1) * y <= x) { index = mid; low = mid + 1; } else { low = mid + 1; } } } if (index == bs.size()) { ans = (ans + x) % mod; } else { if (((pp[i].lr - bs.get(index) + 1) * y) > x) throw new RuntimeException("NO"); ans = (ans + (((pp[i].lr - bs.get(index) + 1) * y) % mod)) % mod; bs.remove(bs.get(index), 1); } } else { ans = (ans + (((ar[pp[i].index][1] - ar[pp[i].index][0]) * y) % mod)) % mod; bs.insert(pp[i].lr + 1l); } } out.println(ans % mod); } class lr implements Comparable<lr> { int lr; int type; int index; public int compareTo(DTVShows.lr o) { if (this.lr == o.lr) return this.type - o.type; return this.lr - o.lr; } public lr(int lr, int type, int index) { this.lr = lr; this.type = type; this.index = index; } } } static class BSTCustom<T extends Comparable<? super T>> { private Node<T> __root; private Node<T> __tempnode; private Node<T> __tempnode1; private long __size; private boolean __multi; public BSTCustom() { __root = null; __size = 0; __multi = false; } public BSTCustom(boolean __multi) { __root = null; __size = 0; this.__multi = __multi; } private Node<T> remove(Node<T> temp, T data, long count) { if (temp == null) return temp; int _comparator = data.compareTo(temp.data); if (_comparator < 0) temp._left = remove(temp._left, data, count); else if (_comparator > 0) temp._right = remove(temp._right, data, count); else { if (__multi && count < temp.count && temp.count > 1) { __size -= count; temp.count -= count; } else { __size -= temp.count; if (temp._left == null && temp._right == null) return null; else if (temp._left == null) return temp._right; else if (temp._right == null) return temp._left; else { __tempnode = minValue(temp._right); temp.data = __tempnode.data; temp.count = __tempnode.count; temp._right = remove(temp._right, __tempnode.data, __tempnode.count); __size += temp.count; } } } // for __leftside and _rightside count if (temp._left != null) temp._leftside = temp._left._leftside + temp._left._rightside + temp._left.count; else temp._leftside = 0; if (temp._right != null) temp._rightside = temp._right._leftside + temp._right._rightside + temp._right.count; else temp._rightside = 0; temp._height = Math.max(getheight(temp._left), getheight(temp._right)) + 1; //Balancing long diff = getDiff(temp); if (diff > 1) { if (getDiff(temp._left) >= 0) { temp = rightRotate(temp); } else { temp._left = leftRotate(temp._left); temp = rightRotate(temp); } } else if (diff < -1) { if (getDiff(temp._right) <= 0) { temp = leftRotate(temp); } else { temp._right = rightRotate(temp._right); temp = leftRotate(temp); } } return temp; } public T get(long index) { __tempnode = __root; long current = 0; while (__tempnode != null) { if (__tempnode._left == null) { if (__tempnode.count + current > index) return __tempnode.data; else { current += __tempnode.count; __tempnode = __tempnode._right; } } else { if (current + __tempnode._leftside > index) __tempnode = __tempnode._left; else if (current + __tempnode._leftside + __tempnode.count > index) return __tempnode.data; else { current += __tempnode.count + __tempnode._leftside; __tempnode = __tempnode._right; } } } return null; } private Node<T> minValue(Node<T> temp) { __tempnode = temp; while (__tempnode._left != null) __tempnode = __tempnode._left; return __tempnode; } public void insert(T data, long... count) { if (count.length == 0) __root = insert(__root, data, 1); else if (count[0] > 0) __root = insert(__root, data, count[0]); } public void remove(T data, long... count) { if (count.length == 0) __root = remove(__root, data, 1); else if (count[0] > 0) __root = remove(__root, data, count[0]); } private Node<T> insert(Node<T> temp, T data, long count) { if (temp == null) { if (__multi) { __size += count; return new Node<>(data, count); } else { __size++; return new Node<>(data); } } int _comparator = data.compareTo(temp.data); if (_comparator < 0) temp._left = insert(temp._left, data, count); else if (_comparator > 0) temp._right = insert(temp._right, data, count); else if (__multi) { __size += count; temp.count += count; } // for __leftside and _rightside count if (temp._left != null) temp._leftside = temp._left._leftside + temp._left._rightside + temp._left.count; else temp._leftside = 0; if (temp._right != null) temp._rightside = temp._right._leftside + temp._right._rightside + temp._right.count; else temp._rightside = 0; temp._height = Math.max(getheight(temp._left), getheight(temp._right)) + 1; //Balancing long diff = getDiff(temp); if (diff > 1) { if (data.compareTo(temp._left.data) < 0) { temp = rightRotate(temp); } else if (data.compareTo(temp._left.data) > 0) { temp._left = leftRotate(temp._left); temp = rightRotate(temp); } } else if (diff < -1) { if (data.compareTo(temp._right.data) > 0) { temp = leftRotate(temp); } else if (data.compareTo(temp._right.data) < 0) { temp._right = rightRotate(temp._right); temp = leftRotate(temp); } } return temp; } private Node<T> rightRotate(Node<T> temp) { __tempnode = temp._left; __tempnode1 = __tempnode._right; __tempnode._right = temp; temp._left = __tempnode1; //height updation temp._height = Math.max(getheight(temp._left), getheight(temp._right)) + 1; __tempnode._height = Math.max(getheight(__tempnode._left), getheight(__tempnode._right)) + 1; //count updation if (temp._left != null) temp._leftside = temp._left._leftside + temp._left._rightside + temp._left.count; else temp._leftside = 0; if (temp._right != null) temp._rightside = temp._right._leftside + temp._right._rightside + temp._right.count; else temp._rightside = 0; if (__tempnode._left != null) __tempnode._leftside = __tempnode._left._leftside + __tempnode._left._rightside + __tempnode._left.count; else __tempnode._leftside = 0; if (__tempnode._right != null) __tempnode._rightside = __tempnode._right._leftside + __tempnode._right._rightside + __tempnode._right.count; else __tempnode._rightside = 0; return __tempnode; } private Node<T> leftRotate(Node<T> temp) { __tempnode = temp._right; __tempnode1 = __tempnode._left; __tempnode._left = temp; temp._right = __tempnode1; //height updation temp._height = Math.max(getheight(temp._left), getheight(temp._right)) + 1; __tempnode._height = Math.max(getheight(__tempnode._left), getheight(__tempnode._right)) + 1; //count updation if (temp._left != null) temp._leftside = temp._left._leftside + temp._left._rightside + temp._left.count; else temp._leftside = 0; if (temp._right != null) temp._rightside = temp._right._leftside + temp._right._rightside + temp._right.count; else temp._rightside = 0; if (__tempnode._left != null) __tempnode._leftside = __tempnode._left._leftside + __tempnode._left._rightside + __tempnode._left.count; else __tempnode._leftside = 0; if (__tempnode._right != null) __tempnode._rightside = __tempnode._right._leftside + __tempnode._right._rightside + __tempnode._right.count; else __tempnode._rightside = 0; return __tempnode; } private long getDiff(Node<T> temp) { if (temp == null) return 0; return getheight(temp._left) - getheight(temp._right); } public long getheight(Node<T> temp) { if (temp == null) return 0; return temp._height; } public long size() { return this.__size; } private class Node<T> { T data; Node<T> _left; Node<T> _right; long _leftside; long _rightside; long _height; long count; public Node(T data) { this.data = data; this._left = null; this._right = null; this._leftside = 0; this._rightside = 0; this._height = 1; this.count = 1; } public Node(T data, long count) { this.data = data; this._left = null; this._right = null; this._leftside = 0; this._rightside = 0; this._height = 1; this.count = count; } } } 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 integer = 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') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long integer = 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') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
bf929821aecd42058d607ea19fdbdc0e
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Div2_523D { static int N; static long X; static long Y; static final long MOD = 1_000_000_007; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer inputData = new StringTokenizer(reader.readLine()); N = Integer.parseInt(inputData.nextToken()); X = Integer.parseInt(inputData.nextToken()); Y = Integer.parseInt(inputData.nextToken()); TreeSet<Integer> times = new TreeSet<>(); int[] l = new int[N]; int[] r = new int[N]; for (int i = 0; i < N; i++) { inputData = new StringTokenizer(reader.readLine()); l[i] = Integer.parseInt(inputData.nextToken()); r[i] = Integer.parseInt(inputData.nextToken()) + 1; times.add(l[i]); times.add(r[i]); } TreeMap<Integer, Integer> map = new TreeMap<>(); ArrayList<Integer> rMap = new ArrayList<>(times); int nI = 0; for (int t : times) { map.put(t, nI++); } for (int i = 0; i < N; i++) { l[i] = map.get(l[i]); r[i] = map.get(r[i]); } int[] delta = new int[nI]; for (int i = 0; i < N; i++) { delta[l[i]]++; delta[r[i]]--; } ArrayList<Integer> lUsed = new ArrayList<>(); int cur = 0; long ans = 0; for (int i = 0; i < nI; i++) { if (delta[i] > 0) { int nAdd = delta[i]; cur += nAdd; for (int j = 1; j <= nAdd; j++) { if (!lUsed.isEmpty()) { int last = lUsed.get(lUsed.size() - 1); long eCost = (rMap.get(i) - rMap.get(last)) * Y; if (eCost < X - Y) { ans = (ans + eCost) % MOD; lUsed.remove(lUsed.size() - 1); } else { ans = (ans + X - Y) % MOD; } } else { ans = (ans + X - Y) % MOD; } } } else if (delta[i] < 0) { int nRem = -delta[i]; cur -= nRem; for (int j = 1; j <= nRem; j++) { lUsed.add(i); } } if (i + 1 < nI) { ans = (ans + (cur * Y % MOD) * (rMap.get(i + 1) - rMap.get(i)) % MOD) % MOD; } } printer.println(ans); printer.close(); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
146deb19ad8a7ac6184b766d8b976f65
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.util.InputMismatchException; import java.util.logging.Level; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.IllegalFormatException; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.util.logging.Logger; import java.io.Serializable; import java.util.List; import java.io.Writer; import java.util.Queue; import java.util.Comparator; import java.util.ArrayDeque; import java.util.Collections; import java.util.ConcurrentModificationException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pili */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int numTvShows = in.nextInt(); long initCost = in.nextInt(); long perMinute = in.nextInt(); long mod = (long) Math.pow(10, 9) + 7; PriorityQueue<Integer> start = new PriorityQueue<>(); PriorityQueue<Integer> end = new PriorityQueue<>(); for (int i = 0; i < numTvShows; i++) { int s = in.nextInt(); int e = in.nextInt(); start.add(s); end.add(e); } MinMaxPriorityQueue<Integer> returns = MinMaxPriorityQueue.create(); MinMaxPriorityQueue<Integer> rentals = MinMaxPriorityQueue.create(); while (!end.isEmpty()) { int nextE = end.peek(); if (start.peek() != null && start.peek() <= end.peek()) { int nextS = start.peek(); // rent an additional tv start.poll(); if (returns.isEmpty()) { // we rent one from the guy rentals.add(nextS); } else { // do we want to rent from the guy, or do we want to grab the last one we didn't use? // lets check the top return. int r = returns.peekLast(); // is it cheaper to use that one or get a new one? // so the rental fee covers the first minute, okay // cost of renting the last one until now // now = 4 // r = 2 // 2 * perMinute long costOfRental = (nextS - r) * perMinute; if (initCost <= costOfRental) { rentals.add(nextS); } else { returns.pollLast(); } } } else { // either return a tv or save it. // lets dump the return tv into the return queue returns.add(nextE); end.poll(); } } // now lets calculate our cost long currRenting = 0; long lastTick = 0; BigInteger acc = BigInteger.ZERO; while (!returns.isEmpty()) { Integer nextS = rentals.peekFirst(); Integer nextE = returns.peekFirst(); if (nextS != null && nextS <= nextE) { acc = acc.add(BigInteger.valueOf(initCost)); acc = acc.add(BigInteger.valueOf((nextS - lastTick) * currRenting * perMinute)); currRenting++; rentals.pollFirst(); lastTick = nextS; } else { acc = acc.add(BigInteger.valueOf((nextE - lastTick) * currRenting * perMinute)); currRenting--; returns.pollFirst(); lastTick = nextE; } acc = acc.mod(BigInteger.valueOf(mod)); } out.println(acc); } } 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 final class MinMaxPriorityQueue<E> extends AbstractQueue<E> { private final Heap minHeap; private final Heap maxHeap; final int maximumSize; private Object[] queue; private int size; private int modCount; private static final int EVEN_POWERS_OF_TWO = 0x55555555; private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa; private static final int DEFAULT_CAPACITY = 11; public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() { return new MinMaxPriorityQueue.Builder<Comparable>(Ordering.natural()).create(); } private MinMaxPriorityQueue(MinMaxPriorityQueue.Builder<? super E> builder, int queueSize) { Ordering<E> ordering = builder.ordering(); this.minHeap = new Heap(ordering); this.maxHeap = new Heap(ordering.reverse()); minHeap.otherHeap = maxHeap; maxHeap.otherHeap = minHeap; this.maximumSize = builder.maximumSize; // TODO(kevinb): pad? this.queue = new Object[queueSize]; } public int size() { return size; } public boolean add(E element) { offer(element); return true; } public boolean addAll(Collection<? extends E> newElements) { boolean modified = false; for (E element : newElements) { offer(element); modified = true; } return modified; } public boolean offer(E element) { Preconditions.checkNotNull(element); modCount++; int insertIndex = size++; growIfNeeded(); // Adds the element to the end of the heap and bubbles it up to the correct // position. heapForIndex(insertIndex).bubbleUp(insertIndex, element); return size <= maximumSize || pollLast() != element; } public E poll() { return isEmpty() ? null : removeAndGet(0); } E elementData(int index) { return (E) queue[index]; } public E peek() { return isEmpty() ? null : elementData(0); } private int getMaxElementIndex() { switch (size) { case 1: return 0; // The lone element in the queue is the maximum. case 2: return 1; // The lone element in the maxHeap is the maximum. default: // The max element must sit on the first level of the maxHeap. It is // actually the *lesser* of the two from the maxHeap's perspective. return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2; } } public E pollFirst() { return poll(); } public E peekFirst() { return peek(); } public E pollLast() { return isEmpty() ? null : removeAndGet(getMaxElementIndex()); } public E peekLast() { return isEmpty() ? null : elementData(getMaxElementIndex()); } MinMaxPriorityQueue.MoveDesc<E> removeAt(int index) { Preconditions.checkPositionIndex(index, size); modCount++; size--; if (size == index) { queue[size] = null; return null; } E actualLastElement = elementData(size); int lastElementAt = heapForIndex(size).swapWithConceptuallyLastElement(actualLastElement); if (lastElementAt == index) { // 'actualLastElement' is now at 'lastElementAt', and the element that was at 'lastElementAt' // is now at the end of queue. If that's the element we wanted to remove in the first place, // don't try to (incorrectly) trickle it. Instead, just delete it and we're done. queue[size] = null; return null; } E toTrickle = elementData(size); queue[size] = null; MinMaxPriorityQueue.MoveDesc<E> changes = fillHole(index, toTrickle); if (lastElementAt < index) { // Last element is moved to before index, swapped with trickled element. if (changes == null) { // The trickled element is still after index. return new MinMaxPriorityQueue.MoveDesc<E>(actualLastElement, toTrickle); } else { // The trickled element is back before index, but the replaced element // has now been moved after index. return new MinMaxPriorityQueue.MoveDesc<E>(actualLastElement, changes.replaced); } } // Trickled element was after index to begin with, no adjustment needed. return changes; } private MinMaxPriorityQueue.MoveDesc<E> fillHole(int index, E toTrickle) { Heap heap = heapForIndex(index); // We consider elementData(index) a "hole", and we want to fill it // with the last element of the heap, toTrickle. // Since the last element of the heap is from the bottom level, we // optimistically fill index position with elements from lower levels, // moving the hole down. In most cases this reduces the number of // comparisons with toTrickle, but in some cases we will need to bubble it // all the way up again. int vacated = heap.fillHoleAt(index); // Try to see if toTrickle can be bubbled up min levels. int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle); if (bubbledTo == vacated) { // Could not bubble toTrickle up min levels, try moving // it from min level to max level (or max to min level) and bubble up // there. return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle); } else { return (bubbledTo < index) ? new MinMaxPriorityQueue.MoveDesc<E>(toTrickle, elementData(index)) : null; } } private E removeAndGet(int index) { E value = elementData(index); removeAt(index); return value; } private Heap heapForIndex(int i) { return isEvenLevel(i) ? minHeap : maxHeap; } static boolean isEvenLevel(int index) { int oneBased = ~~(index + 1); // for GWT Preconditions.checkState(oneBased > 0, "negative index"); return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO); } public Iterator<E> iterator() { return new QueueIterator(); } public void clear() { for (int i = 0; i < size; i++) { queue[i] = null; } size = 0; } public Object[] toArray() { Object[] copyTo = new Object[size]; System.arraycopy(queue, 0, copyTo, 0, size); return copyTo; } static int initialQueueSize( int configuredExpectedSize, int maximumSize, Iterable<?> initialContents) { // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY int result = (configuredExpectedSize == MinMaxPriorityQueue.Builder.UNSET_EXPECTED_SIZE) ? DEFAULT_CAPACITY : configuredExpectedSize; // Enlarge to contain initial contents if (initialContents instanceof Collection) { int initialSize = ((Collection<?>) initialContents).size(); result = Math.max(result, initialSize); } // Now cap it at maxSize + 1 return capAtMaximumSize(result, maximumSize); } private void growIfNeeded() { if (size > queue.length) { int newCapacity = calculateNewCapacity(); Object[] newQueue = new Object[newCapacity]; System.arraycopy(queue, 0, newQueue, 0, queue.length); queue = newQueue; } } private int calculateNewCapacity() { int oldCapacity = queue.length; int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); return capAtMaximumSize(newCapacity, maximumSize); } private static int capAtMaximumSize(int queueSize, int maximumSize) { return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow } public static final class Builder<B> { private static final int UNSET_EXPECTED_SIZE = -1; private final Comparator<B> comparator; private int expectedSize = UNSET_EXPECTED_SIZE; private int maximumSize = Integer.MAX_VALUE; private Builder(Comparator<B> comparator) { this.comparator = Preconditions.checkNotNull(comparator); } public <T extends B> MinMaxPriorityQueue<T> create() { return create(Collections.<T>emptySet()); } public <T extends B> MinMaxPriorityQueue<T> create(Iterable<? extends T> initialContents) { MinMaxPriorityQueue<T> queue = new MinMaxPriorityQueue<T>( this, initialQueueSize(expectedSize, maximumSize, initialContents)); for (T element : initialContents) { queue.offer(element); } return queue; } // safe "contravariant cast" private <T extends B> Ordering<T> ordering() { return Ordering.from((Comparator<T>) comparator); } } static class MoveDesc<E> { final E toTrickle; final E replaced; MoveDesc(E toTrickle, E replaced) { this.toTrickle = toTrickle; this.replaced = replaced; } } private class Heap { final Ordering<E> ordering; Heap otherHeap; Heap(Ordering<E> ordering) { this.ordering = ordering; } int compareElements(int a, int b) { return ordering.compare(elementData(a), elementData(b)); } MinMaxPriorityQueue.MoveDesc<E> tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle) { int crossOver = crossOver(vacated, toTrickle); if (crossOver == vacated) { return null; } // Successfully crossed over from min to max. // Bubble up max levels. E parent; // If toTrickle is moved up to a parent of removeIndex, the parent is // placed in removeIndex position. We must return that to the iterator so // that it knows to skip it. if (crossOver < removeIndex) { // We crossed over to the parent level in crossOver, so the parent // has already been moved. parent = elementData(removeIndex); } else { parent = elementData(getParentIndex(removeIndex)); } // bubble it up the opposite heap if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) { return new MinMaxPriorityQueue.MoveDesc<E>(toTrickle, parent); } else { return null; } } void bubbleUp(int index, E x) { int crossOver = crossOverUp(index, x); Heap heap; if (crossOver == index) { heap = this; } else { index = crossOver; heap = otherHeap; } heap.bubbleUpAlternatingLevels(index, x); } int bubbleUpAlternatingLevels(int index, E x) { while (index > 2) { int grandParentIndex = getGrandparentIndex(index); E e = elementData(grandParentIndex); if (ordering.compare(e, x) <= 0) { break; } queue[index] = e; index = grandParentIndex; } queue[index] = x; return index; } int findMin(int index, int len) { if (index >= size) { return -1; } Preconditions.checkState(index > 0); int limit = Math.min(index, size - len) + len; int minIndex = index; for (int i = index + 1; i < limit; i++) { if (compareElements(i, minIndex) < 0) { minIndex = i; } } return minIndex; } int findMinChild(int index) { return findMin(getLeftChildIndex(index), 2); } int findMinGrandChild(int index) { int leftChildIndex = getLeftChildIndex(index); if (leftChildIndex < 0) { return -1; } return findMin(getLeftChildIndex(leftChildIndex), 4); } int crossOverUp(int index, E x) { if (index == 0) { queue[0] = x; return 0; } int parentIndex = getParentIndex(index); E parentElement = elementData(parentIndex); if (parentIndex != 0) { // This is a guard for the case of the childless uncle. // Since the end of the array is actually the middle of the heap, // a smaller childless uncle can become a child of x when we // bubble up alternate levels, violating the invariant. int grandparentIndex = getParentIndex(parentIndex); int uncleIndex = getRightChildIndex(grandparentIndex); if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { E uncleElement = elementData(uncleIndex); if (ordering.compare(uncleElement, parentElement) < 0) { parentIndex = uncleIndex; parentElement = uncleElement; } } } if (ordering.compare(parentElement, x) < 0) { queue[index] = parentElement; queue[parentIndex] = x; return parentIndex; } queue[index] = x; return index; } int swapWithConceptuallyLastElement(E actualLastElement) { int parentIndex = getParentIndex(size); if (parentIndex != 0) { int grandparentIndex = getParentIndex(parentIndex); int uncleIndex = getRightChildIndex(grandparentIndex); if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { E uncleElement = elementData(uncleIndex); if (ordering.compare(uncleElement, actualLastElement) < 0) { queue[uncleIndex] = actualLastElement; queue[size] = uncleElement; return uncleIndex; } } } return size; } int crossOver(int index, E x) { int minChildIndex = findMinChild(index); // TODO(kevinb): split the && into two if's and move crossOverUp so it's // only called when there's no child. if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) { queue[index] = elementData(minChildIndex); queue[minChildIndex] = x; return minChildIndex; } return crossOverUp(index, x); } int fillHoleAt(int index) { int minGrandchildIndex; while ((minGrandchildIndex = findMinGrandChild(index)) > 0) { queue[index] = elementData(minGrandchildIndex); index = minGrandchildIndex; } return index; } private int getLeftChildIndex(int i) { return i * 2 + 1; } private int getRightChildIndex(int i) { return i * 2 + 2; } private int getParentIndex(int i) { return (i - 1) / 2; } private int getGrandparentIndex(int i) { return getParentIndex(getParentIndex(i)); // (i - 3) / 4 } } private class QueueIterator implements Iterator<E> { private int cursor = -1; private int nextCursor = -1; private int expectedModCount = modCount; private Queue<E> forgetMeNot; private List<E> skipMe; private E lastFromForgetMeNot; private boolean canRemove; public boolean hasNext() { checkModCount(); nextNotInSkipMe(cursor + 1); return (nextCursor < size()) || ((forgetMeNot != null) && !forgetMeNot.isEmpty()); } public E next() { checkModCount(); nextNotInSkipMe(cursor + 1); if (nextCursor < size()) { cursor = nextCursor; canRemove = true; return elementData(cursor); } else if (forgetMeNot != null) { cursor = size(); lastFromForgetMeNot = forgetMeNot.poll(); if (lastFromForgetMeNot != null) { canRemove = true; return lastFromForgetMeNot; } } throw new NoSuchElementException("iterator moved past last element in queue."); } public void remove() { CollectPreconditions.checkRemove(canRemove); checkModCount(); canRemove = false; expectedModCount++; if (cursor < size()) { MinMaxPriorityQueue.MoveDesc<E> moved = removeAt(cursor); if (moved != null) { if (forgetMeNot == null) { forgetMeNot = new ArrayDeque<E>(); skipMe = new ArrayList<E>(3); } if (!foundAndRemovedExactReference(skipMe, moved.toTrickle)) { forgetMeNot.add(moved.toTrickle); } if (!foundAndRemovedExactReference(forgetMeNot, moved.replaced)) { skipMe.add(moved.replaced); } } cursor--; nextCursor--; } else { // we must have set lastFromForgetMeNot in next() Preconditions.checkState(removeExact(lastFromForgetMeNot)); lastFromForgetMeNot = null; } } private boolean foundAndRemovedExactReference(Iterable<E> elements, E target) { for (Iterator<E> it = elements.iterator(); it.hasNext(); ) { E element = it.next(); if (element == target) { it.remove(); return true; } } return false; } private boolean removeExact(Object target) { for (int i = 0; i < size; i++) { if (queue[i] == target) { removeAt(i); return true; } } return false; } private void checkModCount() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private void nextNotInSkipMe(int c) { if (nextCursor < c) { if (skipMe != null) { while (c < size() && foundAndRemovedExactReference(skipMe, elementData(c))) { c++; } } nextCursor = c; } } } } static interface MonotonicNonNull { } static interface GwtCompatible { } static interface Nullable { } static interface CanIgnoreReturnValue { } 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(); } } static interface VisibleForTesting { } static final class Verify { private Verify() { } } static final class Strings { private Strings() { } public static String lenientFormat( String template, Object... args) { template = String.valueOf(template); // null -> "null" if (args == null) { args = new Object[]{"(Object[])null"}; } else { for (int i = 0; i < args.length; i++) { args[i] = lenientToString(args[i]); } } // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template, templateStart, placeholderStart); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } private static String lenientToString(Object o) { try { return String.valueOf(o); } catch (Exception e) { // Default toString() behavior - see Object.toString() String objectToString = o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); // Logger is created inline with fixed name to avoid forcing Proguard to create another class. Logger.getLogger("com.google.common.base.Strings") .log(Level.WARNING, "Exception during lenientFormat for " + objectToString, e); return "<" + objectToString + " threw " + e.getClass().getName() + ">"; } } } static final class CollectPreconditions { static void checkRemove(boolean canRemove) { Preconditions.checkState(canRemove, "no calls to next() since the last call to remove()"); } } static final class ReverseOrdering<T> extends Ordering<T> implements Serializable { final Ordering<? super T> forwardOrder; ReverseOrdering(Ordering<? super T> forwardOrder) { this.forwardOrder = Preconditions.checkNotNull(forwardOrder); } public int compare(T a, T b) { return forwardOrder.compare(b, a); } // how to explain? public <S extends T> Ordering<S> reverse() { return (Ordering<S>) forwardOrder; } public int hashCode() { return -forwardOrder.hashCode(); } public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ReverseOrdering) { ReverseOrdering<?> that = (ReverseOrdering<?>) object; return this.forwardOrder.equals(that.forwardOrder); } return false; } public String toString() { return forwardOrder + ".reverse()"; } } static interface Weak { } static abstract class Ordering<T> implements Comparator<T> { // TODO(kevinb): right way to explain this?? public static <C extends Comparable> Ordering<C> natural() { return (Ordering<C>) NaturalOrdering.INSTANCE; } public static <T> Ordering<T> from(Comparator<T> comparator) { return (comparator instanceof Ordering) ? (Ordering<T>) comparator : new ComparatorOrdering<T>(comparator); } protected Ordering() { } public <S extends T> Ordering<S> reverse() { return new ReverseOrdering<S>(this); } // TODO(kak): Consider removing this public abstract int compare(T left, T right); } static final class Preconditions { private Preconditions() { } public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } public static void checkState(boolean expression, Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } public static int checkPositionIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return Strings.lenientFormat("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return Strings.lenientFormat("%s (%s) must not be greater than size (%s)", desc, index, size); } } } static // TODO(kevinb): the right way to explain this?? final class NaturalOrdering extends Ordering<Comparable> implements Serializable { static final NaturalOrdering INSTANCE = new NaturalOrdering(); public int compare(Comparable left, Comparable right) { Preconditions.checkNotNull(left); // for GWT Preconditions.checkNotNull(right); return left.compareTo(right); } public <S extends Comparable> Ordering<S> reverse() { return (Ordering<S>) ReverseNaturalOrdering.INSTANCE; } public String toString() { return "Ordering.natural()"; } private NaturalOrdering() { } } static final class IntMath { public static int checkedMultiply(int a, int b) { long result = (long) a * b; MathPreconditions.checkNoOverflow(result == (int) result, "checkedMultiply", a, b); return (int) result; } private IntMath() { } } static final class ComparatorOrdering<T> extends Ordering<T> implements Serializable { final Comparator<T> comparator; ComparatorOrdering(Comparator<T> comparator) { this.comparator = Preconditions.checkNotNull(comparator); } public int compare(T a, T b) { return comparator.compare(a, b); } public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ComparatorOrdering) { ComparatorOrdering<?> that = (ComparatorOrdering<?>) object; return this.comparator.equals(that.comparator); } return false; } public int hashCode() { return comparator.hashCode(); } public String toString() { return comparator.toString(); } } static final class MathPreconditions { static void checkNoOverflow(boolean condition, String methodName, int a, int b) { if (!condition) { throw new ArithmeticException("overflow: " + methodName + "(" + a + ", " + b + ")"); } } private MathPreconditions() { } } static // TODO(kevinb): the right way to explain this?? final class ReverseNaturalOrdering extends Ordering<Comparable> implements Serializable { static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering(); public int compare(Comparable left, Comparable right) { Preconditions.checkNotNull(left); // right null is caught later if (left == right) { return 0; } return right.compareTo(left); } public <S extends Comparable> Ordering<S> reverse() { return Ordering.natural(); } public String toString() { return "Ordering.natural().reverse()"; } private ReverseNaturalOrdering() { } } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
ea58811c8872e4b9f361bb812c0d0c91
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ out.println(work()); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } long work() { int n=in.nextInt(); long x=in.nextLong(); long y=in.nextLong(); long[][] A=new long[n][]; for(int i=0;i<n;i++) { A[i]=new long[] {in.nextLong(),in.nextLong()}; } Arrays.sort(A,new Comparator<long[]>() { public int compare(long[] arr1,long[] arr2) { return (int)(arr1[0]-arr2[0]); } }); TreeMap<Long,Integer> map=new TreeMap<>(); long ret=0; for(int i=0;i<n;i++) { long s=A[i][0]; long e=A[i][1]; Long key=map.lowerKey(s); if(key==null||(e-key)*y>x+y*(e-s)) { ret+=(x+y*(e-s)); }else { ret+=(e-key)*y; map.put(key,map.get(key)-1); if(map.get(key)==0)map.remove(key); } map.put(e,map.getOrDefault(e, 0)+1); ret%=mod; } return ret; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(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()); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
59fab34d0278758d341014952f659ad2
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.PriorityQueue; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); long X = ni(), Y = ni(); int mod = 1000000007; int[][] rs = new int[n][]; for(int i = 0;i < n;i++){ rs[i] = na(2); } Arrays.sort(rs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); PriorityQueue<Integer> mlast = new PriorityQueue<>(); PriorityQueue<Integer> wait = new PriorityQueue<>(); long cost = 0; for(int[] r : rs){ while(!wait.isEmpty() && wait.peek() < r[0]){ mlast.add(-wait.poll()); } while(!mlast.isEmpty() && (r[0]+mlast.peek())*Y >= X){ mlast.poll(); } if(mlast.isEmpty()){ cost += X + (r[1]-r[0])*Y; cost %= mod; }else{ cost += (r[1]+mlast.poll())*Y; cost %= mod; } wait.add(r[1]); } out.println(cost); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
fb6fe6fd398d0bfb7872e022f7b480ac
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); class pair { long F, S; pair(long f, long s) { F = f; S = s; } } TreeMap <Long, Integer> mp; void add(long x) { if(mp.containsKey(x)) mp.put(x, mp.get(x) + 1); else mp.put(x, 1); } void remove(long x) { if(mp.get(x) == 1) mp.remove(x); else mp.put(x, mp.get(x) - 1); } void solve() { //SZ = sieve(); //SZ = 1000001; int n = ni(); long x = nl(), y = nl(); pair a[] = new pair[n]; for(int i = 0; i < n; i++) a[i] = new pair(nl(), nl()); Arrays.sort(a, (pair p, pair q) -> { if(p.F != q.F) return (int)(p.F - q.F); return (int)(p.S - q.S); }); mp = new TreeMap<>(); long ans = 0; for(pair p : a) { long u = x + y * (p.S - p.F); Long k = mp.lowerKey(p.F); if(k == null) { ans = (ans + u) % mod; add(p.S); } else { long v = y * (p.S - k); if(u <= v) { ans = (ans + u) % mod; add(p.S); } else { ans = (ans + v) % mod; remove(k); add(p.S); } } } out.println(ans); } //--------- Extra Template ----------- int P[], S[], SZ, NP = 15485900; boolean isP[]; boolean isPrime(long n) { if(n <= 1) return false; if(n <= 3) return true; if(n%2 == 0 || n%3 == 0) return false; for(long i = 5; i * i <= n; i += 6) { if(n % i == 0 || n % (i + 2) == 0) return false; } return true; } int sieve() { int i, j, n = NP; isP = new boolean[n]; S = new int[n]; for(i = 3; i < n; i += 2) { isP[i] = true; S[i-1] = 2; S[i] = i; } isP[2] = true; S[1] = 1; //(UD) for(i = 3; i * i <= n; i += 2) { if( !isP[i] ) continue; for(j = i * i; j < n; j += i) { isP[j] = false; if(S[j] == j) S[j] = i; } } P = new int[n]; P[0] = 2; j = 1; for(i = 3; i < n; i += 2) { if ( isP[i] ) P[j++] = i; } P = Arrays.copyOf(P, j); return j; } long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
1da80ba2ed9c40c0994765bd4f9cc05b
train_002.jsonl
1542901500
There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y &lt; x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { class Node implements Comparable<Node>{ int l; int r; public Node(int x,int y){ this.l=x; this.r=y; } public int compareTo(Node c){ int t=Integer.compare(c.r,this.r); return t; } } void solve() { int n=ni(); long x=ni(),y=ni(); Node p[]=new Node[n]; for(int i=0;i<n;i++){ p[i]=new Node(ni(),ni()); } if(x<=y){ long ans=0; for(Node nd : p) ans+=x+y*(nd.r-nd.l); pw.println(ans); return; } PriorityQueue<Integer> q=new PriorityQueue<>(); for(int i=0;i<n;i++){ q.offer(p[i].l); q.offer(p[i].r); q.offer(p[i].r+1); // if(i==1) System.out.println(p[i].l+" "+p[i].r); } int sz=0; HashMap<Integer,Integer> mp=new HashMap<>(); int rev[]=new int[5*n+1]; while(!q.isEmpty()){ int id=q.poll(); if(!mp.containsKey(id)){ mp.put(id,++sz); rev[sz]=id; } } ArrayList<Integer> vec[]=new ArrayList[sz+1]; ArrayList<Integer> vec2[]=new ArrayList[sz+1]; for(int i=1;i<=sz;i++) vec[i]=new ArrayList<>(); for(int i=1;i<=sz;i++) vec2[i]=new ArrayList<>(); for(int i=0;i<n;i++){ int l=mp.get(p[i].l),r=mp.get(p[i].r+1); vec[l].add(i); if(r<=sz) vec2[r].add(i); } long ans=0; PriorityQueue<Node> qu=new PriorityQueue<>(); Node ass[]=new Node[n]; for(int i=1;i<=sz;i++){ for(int id : vec2[i]){ qu.offer(new Node(ass[id].l,ass[id].r)); } int l=i; out: for(int id: vec[i]) { int r=mp.get(p[id].r); while (!qu.isEmpty()) { Node nd = qu.poll(); if(y*(rev[l]-rev[nd.r])<=x){ ass[id]=new Node(nd.l,r); continue out; }else { ans=add(ans,add(x,mul(y,(rev[nd.r]-rev[nd.l])))); } } ass[id]=new Node(l,r); } } while(!qu.isEmpty()){ Node nd=qu.poll(); ans=add(ans,add(x,mul(y,(rev[nd.r]-rev[nd.l])))); } pw.println(ans); } long add(long x,long y){ if(x>=M) x%=M; if(y>=M) y%=M; x+=y; if(x>=M) x-=M; return x; } long mul(long x,long y) { if(x>=M) x%=M; if(y>=M) y%=M; x *= y; if (x >= M) x %= M; return x; } long M = (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9", "6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27", "2 1000000000 2\n1 2\n2 3"]
2 seconds
["60", "142", "999999997"]
NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch: Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.
Java 8
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
6f4629e2dd9bca7980c8ee4f2e4b3edd
The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y &lt; x \le 10^9$$$)Β β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.
2,000
Print exactly one integerΒ β€” the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.
standard output
PASSED
34e8989fb3621e59ab27b18760d4cf15
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.Scanner; import java.util.HashSet; public class Badge{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n+1]; a[0] = 0; for(int i=1;i<=n;i++){ a[i]=sc.nextInt(); } HashSet<Integer> hs=new HashSet<>(); for(int i=1;i<=n;i++){ hs.add(i); for(int j=i;;j=a[j]){ if(!hs.add(a[j])){ System.out.print(a[j]+" "); hs.clear(); break; } } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
f83c7f7f75a9c7463400bbd9efcbeac2
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; public class CodeForces { public static void main(String[] args) { Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = input.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = input.nextInt() - 1; } for (int i = 0; i < n; i++) { if (array[i] == i) { System.out.print(i + 1 + " "); } else { boolean[] arr = new boolean[n]; arr[i] = true; int z = array[i]; while (!arr[z]) { arr[z] = true; z = array[z]; } System.out.print(z + 1 + " "); } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
1e3b9a727608122faa11fdfa004ae4fc
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); int input[]=new int[N+1]; //int k=in.nextInt(); //long FinalAns=0; for (int i = 1; i <= N; i++) { input[i]=in.nextInt(); } for(int i=1;i<=N;i++){ int visit[]=new int[N+1]; System.out.print(val(i,input,1,N,visit)+" "); // System.out.println("*********"); } //System.out.println(FinalAns); } static int val(int i,int tar[],int c,int N,int[] v){ // System.out.println(i+" "+tar[i]+" "+c); if(v[i]!=0){ return i; } v[i]++; if(c==N){ return tar[i]; } return val(tar[i],tar,c+1,N,v); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public 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; } public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = new Integer(this.nextInt()); return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static int[] uwiSieve(int n) { if (n <= 32) { int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int i = 0; i < tp; i++) { for (int j = i; j < sup; j += tp) isp[j] |= ptn[i]; } } // 3,5,7 // 2x+3=n int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14 }; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; for (int q = pp; q <= h; q += p) isp[q >> 5] |= 1 << (q & 31); } } return Arrays.copyOf(ret, pos); } public static int[] radixSort(int[] f){ return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;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 < n;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } } } // for(Map.Entry<Integer,Integer> Test: map.entrySet()){ // int Key=Test.getKey(); // int val=Test.getValue(); // } // HashMap<Integer,Integer> map=new HashMap<>(); // for(int i=0;i<;i++){ // ch=input[i]; // if(map.containsKey(ch)) // map.put(ch,map.get(ch)+1); // else // map.put(ch,1); // } // //
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
736c4bb6b54256b582eb9eaabc3fcd8c
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; public class Miksha { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=sc.nextInt(); for(int i=1;i<=n;i++) { int f[]=new int[n+1]; f[i]++; int t=i; for(int j=1;j<=n;j++) { f[a[t]]++; if(f[a[t]]==2) { System.out.print(a[t]+" "); break; } t=a[t]; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
64f8fb0044be9dd54b15bddda6947beb
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.InputMismatchException; import java.io.IOException; import java.util.Comparator; import java.io.InputStream; 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); Scanner sc=new Scanner(System.in); int n=in.nextInt(); int visited[]=new int[n]; Arrays.fill(visited,0); int ser[]=new int[n]; for(int i=0;i<n;i++) ser[i]=in.nextInt()-1; for(int i=0;i<n;i++){ Arrays.fill(visited,0); dfs(visited,ser,i); } out.close(); } static void dfs(int vis[],int ser[],int node){ if(vis[node]!=1){ vis[node]=1; dfs(vis,ser,ser[node]); } else{ System.out.print((node+1)+" "); } } 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 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
84e7f218bc966fce5e5dab0528a9ce26
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Codeforces{ BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); PrintWriter out =new PrintWriter(System.out); StringTokenizer st =new StringTokenizer(""); String next(){ if(!st.hasMoreTokens()){ try{ st=new StringTokenizer(br.readLine()); } catch(Exception e){ } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } public static void main(String[] args) { new Codeforces().solve(); } Node node[]; int n=0; int bfs(int start){ ArrayDeque<Integer> q=new ArrayDeque<>(); boolean vis[] =new boolean[n+1]; vis[start] =true; q.add(start); while(q.size()!=0){ int curr = q.poll(); for(int i:node[curr].adj){ if(!vis[i]){ q.add(i); vis[i]=true; } else return i; } } return -1; } void solve(){ n=nextInt(); node =new Node[n+1]; for(int i=0;i<=n;i++) node[i]=new Node(); for(int i=1;i<=n;i++){ int x=nextInt(); node[i].adj.add(x); } for(int i=1;i<=n;i++){ out.print(bfs(i)+" "); } out.close(); } } class Node{ List<Integer> adj =new ArrayList<>(); }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
a16e139e2966a34dc7ab8ae1ccdba7b3
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int a[]=new int[n]; for(int i=0; i<n; i++) { a[i]=in.nextInt()-1; } for(int i=0;i<n;i++) { boolean visited[]=new boolean[n]; for(int j=0;j<n;j++) { visited[j]=false; } int p=i; visited [p]=true; while(true) { if(!visited[a[p]]) visited[a[p]]=true; else { System.out.print((a[p]+1)+" "); break; } p=a[p]; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
9fd4c583f63b96e77c596a382466deb3
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Ideone { public static void main (String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); HashMap<Integer,Integer> hs=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++){ int n1=in.nextInt(); hs.put(i+1,n1); } for(int i=0;i<n;i++){ int start=i+1; HashMap<Integer,Integer> ths=(HashMap<Integer,Integer>)hs.clone(); while(ths.containsKey(start)){ int temp=ths.get(start); ths.remove(start); start=temp; } System.out.print(start+" "); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
ea5f1c0a3fa89570e4899c043e2fa16e
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.HashMap; import java.util.Scanner; /** * * @author Arpit */ public class JavaApplication168 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int arr[]=new int[n+1]; for (int i = 1; i < n+1; i++) { arr[i]=sc.nextInt(); } for (int j = 1; j <= n; j++) { HashMap<Integer,Integer> hs = new HashMap<>(); int yo=j; while(!hs.containsKey(yo)){ hs.put(yo,1); yo=arr[yo]; } System.out.println(yo); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
95077c920ab6ab22d817fb0b8187a2bf
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
/* package codechef; // 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 Codechef { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(bf.readLine()); String []s=bf.readLine().split(" "); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s[i]); } GraphCalculation gc=new GraphCalculation(); // gc.addedges(1,a[0],false); for(int i=0;i<n;i++) { gc.addedges(i+1,a[i],false); } // System.out.println(gc.printgraph()); StringBuilder sb=new StringBuilder(); for(int i=1;i<=n;i++) { // ArrayList<Integer> al2=new ArrayList<>(); int sangam=gc.applybfs(i); sb.append(sangam+" "); } System.out.println(sb); // System.out.println("the Number of vertices present are "+gc.countvertices()); // System.out.println("the Number of edges present are "+gc.countedges(true)); // System.out.println("the vertices is present ? "+gc.hasvertices(9)); // System.out.println("the edges is present ? "+gc.hasedges(1,2)); // System.out.println("the total graph is like- \n"+gc.printgraph()); // System.out.println("the BFS is like- \n"+gc.applybfs(1)); // System.out.println("the dfs is like- \n"+gc.applydfs(1)); } } class GraphCalculation { HashMap<Integer,LinkedList<Integer>> hm=new HashMap<>(); public void addvertices(Integer s) { hm.put(s,new LinkedList<Integer>()); } public void addedges(Integer source,Integer destination,boolean bidirection) { if(!hm.containsKey(source)) { addvertices(source); } if(!hm.containsKey(destination)) { addvertices(destination); } hm.get(source).add(destination); if(bidirection==true) { hm.get(destination).add(source); } } // public int countvertices() // { // return(hm.keySet().size()); // } // public int countedges(boolean bidirection) // { // int count=0; // for(T s:hm.keySet()) // { // count=count+hm.get(s).size(); // } // if(bidirection==false) // { // count=count/2; // } // return count; // } // public boolean hasvertices(T n) // { // if(hm.containsKey(n)) // return true; // return false; // } // public boolean hasedges(T source,T destination) // { // if(hm.containsKey(source) && hm.containsKey(destination) && hm.get(source).contains(destination)) // return true; // return false; // } public StringBuilder printgraph() { StringBuilder sb=new StringBuilder(); for(Integer i:hm.keySet()) { sb.append(i+"-->"); for(Integer j:hm.get(i)) { sb.append(j+" "); } sb.append("\n"); } return sb; } public int applybfs(Integer n) { int z=hm.keySet().size(); Queue<Integer> pq=new LinkedList<>(); // ArrayList<Integer> al=new ArrayList<>(); // ArrayList<Integer> al2=new ArrayList<>(); boolean minal[]=new boolean[z]; pq.add(n); minal[n-1]=true; while(pq.size()!=0) { Integer a=pq.peek(); for(Integer r:hm.get(a)) { if(minal[r-1]) { return r; } else { pq.add(r); minal[r-1]=true; } } pq.poll(); } return 0; } // public StringBuilder applybfs(T n) // { // Queue<T> pq=new LinkedList<>(); // int k=hm.keySet().size(); // boolean visited[]=new boolean[k]; // StringBuilder sb=new StringBuilder(); // visited[n]=true; // pq.add(n); // while(pq.size()!=0) // { // T r=pq.poll(); // sb.append(r+" "); // for(T z:hm.get(r)) // { // if(!visited[(int)z]) // { // pq.add(z); // visited[z]=true; // } // } // } // return sb; // } // public ArrayList applydfs(T n) // { // ArrayList<T> al=new ArrayList<>(); // Stack<T> st=new Stack<>(); // st.push(n); // while(st.size()!=0) // { // T a=st.pop(); // al.add(a); // for(T r:hm.get(a)) // { // if(!st.contains(r) && !al.contains(r)) // { // st.push(r); // } // } // } // return al; // } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
912a458e19a9f9792c4320e2c70f4fdb
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i]=scan.nextInt(); if(n==1){ System.out.println(a[0]); System.exit(0); } for(int i=0;i<n;i++){ Set ww=new HashSet(); ww.add(i+1); ww.add( a[i]); int r=a[i]; for(int j=1;j<n;j++){ int t=r; if(!ww.add(a[t-1])) { System.out.println(a[t-1]); break; } r=a[t-1]; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
5adc8bbb5b3603962c22f6d89a0cc513
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class CF1020_D2_B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] p = new int[n+1]; for (int i = 1; i < n+1; i++) { p[i] = scanner.nextInt(); } HashSet<Integer> set = new HashSet<>(); for (int i = 1; i <= n; i++) { set.add(i); int x = i; while (true){ x = p[x]; if(set.contains(x)){ System.out.print(x +" "); break; } else { set.add(x); } } set = new HashSet<>(); } System.out.println(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
03c84d7c024c46aec771eec24aca8d97
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { ArrayList<Integer>[] adjList; private void solve() { int n = nextInt(); adjList = new ArrayList[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<>(); adjList[i].add(nextInt()-1); } for (int i = 0; i < n; i++) { int res = depthSearch(i); out.print((res+1) + " "); } } private int depthSearch(int root) { Set<Integer> visited = new HashSet<>(); Stack<Integer> stack = new Stack<>(); int res = -1; stack.push(root); while (!stack.isEmpty()) { int vertex = stack.pop(); if (!visited.contains(vertex)) { visited.add(vertex); for (int v : adjList[vertex]) { stack.push(v); } } else { res = vertex; break; } } return res; } public static void main(String[] args) { new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; private void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("src/input.in")); // out = new PrintWriter(new FileWriter("src/output.out")); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private int nextInt() { return Integer.parseInt(next()); } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return "END_OF_FILE"; } } return st.nextToken(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
4131b08d08b8c0d38de3827ffb814a20
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BBadge solver = new BBadge(); solver.solve(1, in, out); out.close(); } static class BBadge { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int[] ar = new int[n]; in.scanInt(ar, n); for (int i = 0; i < n; i++) { HashSet<Integer> set = new HashSet<>(); int temp = i; while (!set.contains(temp)) { set.add(temp); temp = ar[temp] - 1; } out.print((temp + 1) + " "); } } } 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 integer = 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') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public void scanInt(int[] A, int size) { for (int i = 0; i < size; i++) A[i] = scanInt(); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
9cdb0aac4a49f6aec534e2d60baa5ac2
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.Scanner; public class badge { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); String v = in.nextLine(); int[] arr = new int[n]; for (int i = 0; i < n; i++){ arr[i] = in.nextInt(); } for (int i = 1; i <= n; i++){ int[] charges = new int[n]; charges[i-1] = 1; for (int j = i-1; j < n; j=j+0){ int x = arr[j]; charges[x-1] += 1; if (charges[x-1]==2){ System.out.print(x+" "); break; } j = x-1; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
b5cd78ee61d9cebc1e01d693697b7795
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String [] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Map<Integer, Integer>counts = new HashMap<Integer, Integer>(); Map<Integer, Integer>claims = new HashMap<Integer, Integer>(); ArrayList<Integer>res = new ArrayList<>(); for(int i = 1; i <= n; i++){ counts.put(i, 0); claims.put(i, scanner.nextInt()); } int cur; for(int i = 1; i <= n; i++){ cur = i; while(true){ counts.put(cur, counts.get(cur) + 1); if(counts.get(cur) > 1){ res.add(cur); break; }else{ cur = claims.get(cur); } } for(int k = 1; k <= n; k++){ counts.put(k, 0); } } for(int i = 0; i < n; i++){ System.out.print(res.get(i) + " "); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
5759c52dbcd3a82c4de734890afa1849
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String args[]) { FastScanner in=new FastScanner(); int n=in.nextInt(); int a[]=in.nextArray(n); StringBuilder sb=new StringBuilder(); for(int i=0;i<n;i++) { HashSet<Integer> hset=new HashSet<>(); int j=i+1; while(!hset.contains(j)) { hset.add(j); j=a[j-1]; } sb.append(j+" "); } System.out.println(sb); } /////////////////////////// static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
728c0671a476856ea2d3153437f42569
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.StringTokenizer; public class Main { 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 java.lang.Exception { // your code goes here FastReader in=new FastReader(); int n = in.nextInt(); int[] arr = new int[n] ; for(int i=0;i<n;i++) { arr[i] = in.nextInt(); } for(int i=0;i<n;i++) { Set<Integer> map = new HashSet<>() ; map.add(i+1); int j = i ; while(true) { int next = arr[j] ; if(map.contains(next)) { System.out.print(next+" "); break ; } else { map.add(next); j = next - 1 ; } } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
ecf7ab7889689d07ebf5fca42aabca4d
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; // author @mdazmat9 public class codeforces{ static ArrayList<Integer> list=new ArrayList<>(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int test = 1; for (int ind = 0; ind < test; ind++) { int n=sc.nextInt(); int [] a=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt()-1; } ArrayList<Integer> ans=new ArrayList<>(); for(int i=0;i<n;i++){ list.add(check(a,i)); } for(int i=0;i<n;i++){ out.print((list.get(i)+1)+" "); } } out.flush(); } static int check(int[]a,int start){ int num=a[start]; boolean [] bool=new boolean[a.length]; for(int i=0;i<a.length;i++) bool[i]=false; int ret=-1; bool[start]=true; while (true){ // System.out.println(num+" "+a[num]+" "+bool[num]); if(bool[num]==true){ ret=num; break; } bool[num]=true; num=a[num]; } return ret; } static 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; } } static long gcd(long a , long b) { if(b == 0) return a; return gcd(b , a % b); } } class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public 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(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } class OutputWriter { BufferedWriter writer; public OutputWriter(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i); } public void print(String s) throws IOException { writer.write(s); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.close(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
ab0905a63b2db78923c1dc9a4592a67d
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; // author @mdazmat9 public class CodeForces_CA { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // The fast input should be enough OutputWriter out = new OutputWriter(System.out); // If you don't use the \n the writer will print trash int n=sc.nextInt(); int x=0,y,z; int[]a=new int[n]; int[]res=new int[n]; for(int i=0;i<n;i++) { y=sc.nextInt(); y--; a[i] = y; } int index; for(int i=0;i<n;i++){ int[]b=new int[n]; index=i; b[index]++; while(true){ index=a[index]; b[index]++; if(b[index]==2){ res[x++]=index+1; break; } } // String s=Arrays.toString(b); // System.out.println(s); } for(int i=0;i<n;i++){ System.out.print(res[i]+" "); } } } class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public 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(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } class OutputWriter { BufferedWriter writer; public OutputWriter(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i); } public void print(String s) throws IOException { writer.write(s); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.close(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
f12976b3f208ae9069d5846d2cc4b71a
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.math.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class a{ static int[] count,count1,count2; static int[] arr; static char[] ch,ch1; static int[] darr,farr; static Character[][] mat,mat1; static long x,h; static long maxl; static double dec; static String s; static long minl; static int mx = (int)1e6; static long mod = 998244353l; // static int minl = -1; // static long n; static int n,n1,n2; static long a; static long b; static long c; static long d; static long y,z; static int m; static long k; static String[] str,str1; static Set<Integer> set,set1,set2; static List<Integer> list,list1,list2; static LinkedList<Character> ll; static Map<Integer,Integer> map; static StringBuilder sb,sb1,sb2; public static void solve(){ sb = new StringBuilder(); for(int i = 1 ; i <= n ; i++){ set = new HashSet<>(); int j = i; set.add(j); while(!set.contains(arr[j])){ set.add(arr[j]); j = arr[j]; } sb.append(arr[j]+" "); } System.out.println(sb); } public static void main(String[] args) { FastScanner sc = new FastScanner(); // Scanner sc = new Scanner(System.in); // int t = sc.nextInt(); int t = 1; // int l = 1; while(t > 0){ // a = sc.nextLong(); // b = sc.nextLong(); // c = sc.nextLong(); // d = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // n = sc.nextLong(); n = sc.nextInt(); // n1 = sc.nextInt(); // m = sc.nextInt(); // k = sc.nextLong(); // ch = sc.next().toCharArray(); // ch1 = sc.next().toCharArray(); arr = new int[n+1]; for(int i = 1 ; i <= n ; i++){ arr[i] = sc.nextInt(); } // darr = new int[n]; // for(int i = 0; i < n ; i++){ // darr[i] = sc.nextInt(); // } // farr = new int[n]; // for(int i = 0; i < n ; i++){ // farr[i] = sc.nextInt(); // } // mat = new Character[n][m]; // for(int i = 0 ; i < n ; i++){ // String s = sc.next(); // for(int j = 0 ; j < m ; j++){ // mat[i][j] = s.charAt(j); // } // } // str = new String[n]; // for(int i = 0 ; i < n ; i++) // str[i] = sc.next(); // System.out.println(solve()?"YES":"NO"); solve(); // System.out.println(solve()); t -= 1; } } public static int log(long n){ if(n == 0 || n == 1) return 0; if(n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if(den == 0) return 0; return (int)(num/den); } public static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } public static long gcd(long a,long b){ if(b%a == 0) return a; return gcd(b%a,a); } // public static void swap(int i,int j){ // long temp = arr[j]; // arr[j] = arr[i]; // arr[i] = temp; // } static final Random random=new Random(); static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class Node{ int first; int second; Node(int f,int s){ this.first = f; this.second = s; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
aa62fe941fd977646c97f5d5b184eb28
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); int[] arr = new int[n+1]; int[] ans = new int[n+1]; for (int i = 1 ; i < n+1 ; i++){ arr[i] = Reader.nextInt(); } int current = 1; for (int i = 0 ; i < n ; i++){ //System.out.println(current); boolean[] flagArray = new boolean[10000]; flagArray[current] = true; int curr = arr[current]; flagArray[curr] = true; //System.out.println(curr); for (int j = 0 ; j < n ; j ++){ curr = arr[curr]; //System.out.println(curr); if (flagArray[curr]==true){ ans[current] = curr; //System.out.println(); break; } else{ flagArray[curr] = true; } } current++; } for (int i = 1 ; i < n + 1 ; i++){ System.out.print(ans[i] + " "); } System.out.println(); } } 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 long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
35a190503493449e1c26858c76b92bb1
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; public class Badge{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] inp = new int[n]; for(int i = 0; i < n; ++i) { inp[i] = sc.nextInt(); } solve(n, inp); } public static void solve(int n, int[] a) { boolean br = false; for(int i = 0; i < n; ++i) { int[] vis = new int[n]; for(int k = 0; k < n; ++k) vis[k] = 0; int p = i; while(vis[p] < 2) { vis[p]++; if(vis[p] >= 2) { br = true; break; } p = a[p] - 1; } for(int j = 0; j < n; ++j) { if(vis[j] == 2) { System.out.print((j + 1) + " "); } } } System.out.println(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
bfcfd7c7b97914aeddf5a452e76d8b23
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
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 nirav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scan in = new Scan(inputStream); PrintWriter out = new PrintWriter(outputStream); BBadge solver = new BBadge(); solver.solve(1, in, out); out.close(); } static class BBadge { public void solve(int testNumber, Scan in, PrintWriter out) { int n = in.scanInt(); int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = in.scanInt(); for (int i = 1; i <= n; i++) { int check[] = new int[n + 1]; int j = i; while (true) { if (check[j] >= 1) { out.print(j + " "); break; } else { check[j]++; j = a[j]; } } } } } static class Scan { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public Scan(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; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
5322905fee5b242034f9d59f567a47d2
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
/** * @author Administrator */ import java.util.* ; public class main { static int [][] N = new int[1001][1001]; static int visit_2d_elment = 0; static int count [] ; static { count = new int[1001]; } static int Badge( int a , int n) { if(visit_2d_elment != 0){return 0;} count[a] = count[a] + 1 ; //System.out.print(a); if(count[a] == 2){visit_2d_elment = a ;} else { for( int i = 1 ; i <= n; i++) { if( N[a][i] == 1 ) { a = i ; break; } } Badge( a , n); } return visit_2d_elment; } public static void main(String[] args) { // Problem 1 - Budget Scanner In = new Scanner(System.in); int n = In.nextInt(); int st1; for(int i = 1 ; i <= n ; i++) { int st = In.nextInt(); N [i][st] = 1 ; } for(int i = 1 ; i <= n ; i++) { int out = Badge(i ,n); System.out.print(out + " "); visit_2d_elment = 0; for(int j = 1 ; j <= n ; j++) count[j] = 0 ; } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
6688bdb6d9fb03ff06c50e24f0b19fc4
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.IOException; import java.math.*; public class cp{ public static boolean[] visited; public static int[] nextNode; public static int[] answer; public static int dfs(int node){ if(visited[node] && answer[node]!=-1){ return answer[node]; }else if(visited[node]){ return node; } visited[node]=true; int x=dfs(nextNode[node]); if(x == node){ answer[node]=node; return (-1)*node; }else if(x<0){ answer[node]=-x; return x; } answer[node]=node; return x; } public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer s = new StringTokenizer(br.readLine()); int n = Integer.parseInt(s.nextToken()); s = new StringTokenizer(br.readLine()); int[] edge = new int[n]; for(int i=0;i<n;i++){ edge[i] = Integer.parseInt(s.nextToken()) - 1; } nextNode = edge; for(int i=0;i<n;i++){ HashSet<Integer> visited = new HashSet<Integer>(); int node=i; while(!visited.contains(node)){ visited.add(node); node=nextNode[node]; } System.out.print(node+1+" "); } System.out.println(""); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
cfab8caaa64e4e4e4be60003d8e54358
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.Scanner; //Question C 502 public class Main2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) { a[i] = in.nextInt(); a[i]--; } for(int i=0;i<n;i++) { System.out.print(dfs(i,a,n)+1+" "); } } private static int dfs(int i, int[] a, int n) { boolean[] vis = new boolean[n]; vis[i]=true; int prev = i; int next = a[i]; while(!vis[next]) { vis[next]=true; prev = next; next = a[prev]; } //tada return next; } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
0e9f1183e60d0d1a9af58dd1cc78aeeb
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; public class Main { private static final int MAXN = 5000; private static final String NO = "NO"; private static final String YES = "YES"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 1000000007L; void solve() { int n = ni(); int[] p = new int[n + 1]; for (int i = 1; i <= n; i++) p[i] = ni(); int cnt[] = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = i;; j = p[j]) { if (cnt[j] != i) cnt[j] = i; else { out.print(j + " "); break; } } } } long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private boolean vis[]; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n) { if (!(isSpaceChar(b))) buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private List<Integer> na2(int n) { List<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) a.add(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } public class Pair<K, V> { /** * Key of this <code>Pair</code>. */ private K key; /** * Gets the key for this pair. * * @return key for this pair */ public K getKey() { return key; } /** * Value of this this <code>Pair</code>. */ private V value; /** * Gets the value for this pair. * * @return value for this pair */ public V getValue() { return value; } /** * Creates a new pair * * @param key The key for this pair * @param value The value to use for this pair */ public Pair(K key, V value) { this.key = key; this.value = value; } /** * <p> * <code>String</code> representation of this <code>Pair</code>. * </p> * * <p> * The default name/value delimiter '=' is always used. * </p> * * @return <code>String</code> representation of this <code>Pair</code> */ @Override public String toString() { return key + "=" + value; } /** * <p> * Generate a hash code for this <code>Pair</code>. * </p> * * <p> * The hash code is calculated using both the name and the value of the * <code>Pair</code>. * </p> * * @return hash code for this <code>Pair</code> */ @Override public int hashCode() { // name's hashCode is multiplied by an arbitrary prime number (13) // in order to make sure there is a difference in the hashCode between // these two parameters: // name: a value: aa // name: aa value: a return key.hashCode() * 13 + (value == null ? 0 : value.hashCode()); } /** * <p> * Test this <code>Pair</code> for equality with another <code>Object</code>. * </p> * * <p> * If the <code>Object</code> to be tested is not a <code>Pair</code> or is * <code>null</code>, then this method returns <code>false</code>. * </p> * * <p> * Two <code>Pair</code>s are considered equal if and only if both the names and * values are equal. * </p> * * @param o the <code>Object</code> to test for equality with this * <code>Pair</code> * @return <code>true</code> if the given <code>Object</code> is equal to this * <code>Pair</code> else <code>false</code> */ @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof Pair) { Pair pair = (Pair) o; if (key != null ? !key.equals(pair.key) : pair.key != null) return false; if (value != null ? !value.equals(pair.value) : pair.value != null) return false; return true; } return false; } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
3f29a5ee8d1f50251361c0f0339a1fb1
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; public class Main { private int V; private ArrayList<Integer> adj[]; Main(int v) { V=v; adj=new ArrayList[v]; for(int i=0;i<v;i++) { adj[i]=new ArrayList(); } } void addedge(int v,int w) { adj[v].add(w); } void dfsutil(int v,boolean visited[],ArrayList<Integer> ar) { visited[v]=true; for(int i:adj[v]) { if(!visited[i]) { dfsutil(i,visited,ar); } else { ar.add(i); return; } } } void dfsfirst() { ArrayList<Integer> ar=new ArrayList<Integer>(); for(int j=0;j<V;j++) { boolean visited[]=new boolean[V]; dfsutil(j,visited,ar); } for(int l:ar) { System.out.print(l+1+" "); } } public static void main(String [] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); Main g=new Main(n); for(int i=0;i<n;i++) { int a=in.nextInt(); g.addedge(i, a-1); } g.dfsfirst(); } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
48d66bf881125352e6ec910610aa5feb
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] p = new int[n + 1]; for (int i = 0; i < n; i++) { p[i + 1] = scanner.nextInt(); } for (int i = 1; i <= n; i++) { int[] arr = new int[n + 1]; int count = i; while (arr[count] != 1) { arr[count]++; count = p[count]; } System.out.println(count); } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
b2ccfece4e4f675e1d83b9cca141b1cb
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int[] stu = new int[n + 1]; for(int i = 1;i <= n;i++) stu[i] = cin.nextInt(); HashMap<Integer,Integer> map = new HashMap<>(); for(int i = 1;i <= n;i++) { map.clear(); int curStu = i; while(true) { if(!map.containsKey(curStu)) map.put(curStu,1); else { int times = map.get(curStu); map.put(curStu,++times); if(times == 2) { System.out.print(curStu + " "); break; } } curStu = stu[curStu]; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
901114ba23d3268220bc70dea7a07a0d
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Problem { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] arr = new int[N+1]; for(int i=1;i<=N;i++)arr[i]=sc.nextInt(); int[] holes = new int[N+1]; for(int i=1;i<=N;i++) { Arrays.fill(holes , 0); int cur = i; while(cur <= N) { if(holes[cur]==1){System.out.print(cur+" ");break;} holes[cur]++; cur=arr[cur]; } } } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
9efcfb9eae7bf042f9ff23a70921ea89
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class sol { int mat[][]; public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=Integer.parseInt(sc.nextLine()); String s[]=sc.nextLine().split(" "); //String str[]=s.split(" "); //System.out.println(s[1]); int mat[][]=new int[n][n]; for(int i=0;i<n;i++){ mat[i][Integer.parseInt(s[i])-1]=1; } String str=graph(mat); System.out.println(str); } public static String graph(int[][] mat){ int []ar=new int[mat.length]; for(int i=0;i<mat.length;i++){ int visited[]=new int[mat.length]; Arrays.fill(visited,0); ar[i]=dfs(visited,mat,i)+1; //ar[i]=1; } String s=""; s=s+ar[0]; for(int i=1;i<ar.length;i++){ s=s+" "+ar[i]; } return s; } public static int dfs(int []visited,int[][] mat,int in){ if(in>=mat.length){ return 0; } if(visited[in]==1){ return in; } else{ visited[in]=1; for(int i=0;i<mat.length;i++){ if(mat[in][i]!=0){ return dfs(visited,mat,i); } } } return 1; } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
e1eb5fdc2283c71e24768c7a4af8cc8b
train_002.jsonl
1533994500
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
256 megabytes
import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; public class Badge { static int n; public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); n = s.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt()-1; } boolean[] visit = new boolean[n]; for(int i=0;i<n;i++) { dfs(i, arr, visit); } } static void dfs(int i, int[] arr, boolean[] visit) { if(visit[i]) { System.out.print(i+1 + " "); return; } visit[i] = true; dfs(arr[i], arr, visit); visit[i] = false; } }
Java
["3\n2 3 2", "3\n1 2 3"]
1 second
["2 2 3", "1 2 3"]
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
1,000
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
standard output
PASSED
243b060ce9546c8d0ae23451272304c2
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.awt.List; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.Vector; public class Main { static Vector<Vector<Pair>> adjlst = new Vector<Vector<Pair>>(); static long dest[] = null; static int n, m, s; static void dijkstra() { for (int i = 0; i < dest.length; i++) { dest[i] = 1 << 27; } dest[s] = 0; PriorityQueue<Pair> q = new PriorityQueue<Pair>(); q.add(new Pair(0, s)); while (q.size() > 0) { int src = q.peek().node; long cost = q.peek().cost; q.poll(); if (dest[src] != cost) continue; for (Pair nxt : adjlst.get(src)) { if (dest[nxt.node] > dest[src] + nxt.cost) { dest[nxt.node] = dest[src] + nxt.cost; q.add(new Pair(cost + nxt.cost, nxt.node)); } } } } public static void main(String[] args) throws IOException { BufferedReader cin = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(cin.readLine()); n = Integer.parseInt(tok.nextToken()); m = Integer.parseInt(tok.nextToken()); s = Integer.parseInt(tok.nextToken()); int f, t, w; adjlst.setSize(n + 1); for (int i = 0; i < adjlst.size(); i++) { adjlst.set(i, new Vector<Pair>()); } dest = new long[n + 1]; Vector<Edge> edg = new Vector<Edge>(); edg.setSize(m); for (int i = 0; i < m; i++) { tok = new StringTokenizer(cin.readLine()); f = Integer.parseInt(tok.nextToken()); t = Integer.parseInt(tok.nextToken()); w = Integer.parseInt(tok.nextToken()); adjlst.get(f).addElement(new Pair(w, t)); adjlst.get(t).addElement(new Pair(w, f)); edg.set(i, new Edge(f, t, w)); } tok = new StringTokenizer(cin.readLine()); int l = Integer.parseInt(tok.nextToken()); dijkstra(); for (int i = 1; i < dest.length; i++) { System.err.println(i + " " + dest[i]); } int res = 0; for (int i = 1; i < dest.length; i++) { if (dest[i] == l) ++res; } for (Edge edge : edg) { if (dest[edge.u] < l && dest[edge.u] + edge.w > l) { int req = (int) (l - dest[edge.u]); int other = edge.w - req; if (dest[edge.v] + other >= l) ++res; } if (dest[edge.v] < l && dest[edge.v] + edge.w > l) { int req = (int) (l - dest[edge.v]); int other = edge.w - req; if(dest[edge.u] + other > l) ++res; } // if (dest[edge.v] < l && dest[edge.u] < l) { // int requ = (int) (l - dest[edge.u]); // int reqv = (int) (l - dest[edge.v]); // if (requ + reqv == edge.w) // --res; // } } System.out.println(res); } } class Edge { int u, v, w; public Edge(int u, int v, int w) { this.u = u; this.v = v; this.w = w; } } class Pair implements Comparable<Pair> { public int node; public long cost; public Pair(long cost, int nxt) { this.node = nxt; this.cost = cost; } public int compareTo(Pair o) { if (cost < o.cost) return -1; if (cost > o.cost) return 1; return 0; } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
7cf322745706ccf2b73818af09f92df3
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
//package round103; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class D { static BufferedReader bf = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static String nextStr() throws IOException { return nextToken(); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static void main(String[] args) throws IOException { int n = nextInt(); int m = nextInt(); int s = nextInt() - 1; City[] c = new City[n]; for (int i = 0; i < n; i++) { c[i] = new City(Integer.MAX_VALUE, i); } c[s].dist = 0; TreeSet<City> set = new TreeSet<City>(); for (int i = 0; i < n; i++) { set.add(c[i]); } ArrayList a[] = new ArrayList[n]; for (int i = 0; i < n; i++) { a[i] = new ArrayList<Road>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = nextInt(); a[u].add(new Road(v, w)); a[v].add(new Road(u, w)); } while (!set.isEmpty()) { City t = set.first(); set.remove(t); for (int i = 0; i < a[t.num].size(); i++) { Road r = (Road)a[t.num].get(i); if (c[t.num].dist + r.len < c[r.to].dist) { set.remove(c[r.to]); c[r.to].dist = c[t.num].dist + r.len; set.add(c[r.to]); } } } int l = nextInt(); int city = 0; int road = 0; for (int i = 0; i < n; i++) { if (c[i].dist == l) { city++; } for (int j = 0; j < a[i].size(); j++) { Road r = (Road)a[i].get(j); int x = Math.min(c[i].dist, c[r.to].dist); int y = Math.max(c[i].dist, c[r.to].dist); double p = x + (r.len + y - x) / 2.0; if (p > l) { if (x < l) { road++; } if (y < l) { road++; } } else if ((int)p == l && x != l && y != l) { road++; } } } out.println(city + road / 2); out.flush(); } static class Road { int to; int len; Road(int t, int l) { to = t; len = l; } } static class City implements Comparable<City> { int dist; int num; City(int d, int n) { dist = d; num = n; } @Override public int compareTo(City o) { if (dist != o.dist) { return dist - o.dist; } else { return num - o.num; } } @Override public boolean equals(Object o) { City c = (City)o; return c.num == num; } @Override public int hashCode() { return ((Object)this).hashCode(); } } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
af6cfed3fd919a1592bae4c734222f79
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } public static void solve() throws IOException { int n = nextInt(); int m = nextInt(); int s = nextInt(); List<Edge>[] edges = new List[n+1]; for (int i = 0; i <=n; i++) edges[i] = new ArrayList<Edge>(); for (int j = 0; j < m; j++) { int v = nextInt(); int u = nextInt(); int w = nextInt(); edges[v].add(new Edge(u, w)); edges[u].add(new Edge(v, w)); } int l=nextInt(); long[] distances = new long[n+1]; int[] pred = new int[n+1]; DijkstraHeap.shortestPaths(edges, s, distances, pred); int ans=0; for (int i=1; i<=n; i++) { // writer.println(pred[i]); if (distances[i]==l) { ans++; } } int k=0; for(int i=1; i<=n; i++) { for(int j=0; j<edges[i].size(); j++) if (distances[i]<l && distances[i]+edges[i].get(j).cost>l && l<=edges[i].get(j).cost+distances[i]-l+distances[edges[i].get(j).t]) { if (l==edges[i].get(j).cost+distances[i]-l+distances[edges[i].get(j).t]) k++; ans++; } } writer.println(ans-k/2); } } class DijkstraHeap { public static void shortestPaths(List<Edge>[] edges, int s, long[] prio, int[] pred) { Arrays.fill(pred, -1); Arrays.fill(prio, Long.MAX_VALUE); prio[s] = 0; Queue<QItem> q = new PriorityQueue<QItem>(); q.add(new QItem(0, s)); while (!q.isEmpty()) { QItem cur = q.poll(); if (cur.prio != prio[cur.u]) continue; for (Edge e : edges[cur.u]) { int v = e.t; long nprio = prio[cur.u] + e.cost; if (prio[v] > nprio) { prio[v] = nprio; pred[v] = cur.u; q.add(new QItem(nprio, v)); } } } } } class Edge { int t, cost; public Edge(int t, int cost) { this.t = t; this.cost = cost; } } class QItem implements Comparable<QItem> { long prio; int u; public QItem(long prio, int u) { this.prio = prio; this.u = u; } public int compareTo(QItem q) { return prio < q.prio ? -1 : prio > q.prio ? 1 : 0; } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
387875abdbfdccdf03e97d0dfe954d54
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.*; public class TaskD { class Road implements Comparable<Road> { int u; int v; int w; Road(int u, int v, int w) { this.u = u; this.v = v; this.w = w; } public int compareTo(Road o) { return w - o.w; } } class State { int node; int dist; State(int node, int dist) { this.node = node; this.dist = dist; } } final int LIM = 2234567; void run() { int n = nextInt(), m = nextInt(); int s = nextInt() - 1; Road[] roads = new Road[m]; ArrayList<Road>[] nodes = new ArrayList[n]; for(int i = 0; i < n; i++) nodes[i] = new ArrayList<Road>(); for(int i = 0; i < m; i++) { int u = nextInt() - 1, v = nextInt() - 1, w = nextInt(); roads[i] = new Road(u, v, w); nodes[u].add(roads[i]); nodes[v].add(roads[i]); } for(int i = 0; i < n; i++) Collections.sort(nodes[i]); int l = nextInt(); int[] d = new int[n]; Arrays.fill(d, -1); State[] q = new State[LIM]; int qt = 0, qh = 0; q[qt++] = new State(s, 0); while(qh < qt) { State top = q[qh++]; if(d[top.node] == -1 || d[top.node] > top.dist) { d[top.node] = top.dist; for(Road r : nodes[top.node]) { if(r.u == top.node) { q[qt++] = new State(r.v, top.dist + r.w); } else { q[qt++] = new State(r.u, top.dist + r.w); } } } else { continue; } } int ans = 0; for(int i = 0; i < n; i++) if(d[i] == l) ans++; for(Road r : roads) { int x1 = d[r.u], x2 = d[r.v]; int loc1 = -1; if(x1 < l && x1 + r.w > l) { loc1 = l - x1; if(x2 + r.w - loc1 < l) loc1 = -1; } int loc2 = -1; if(x2 < l && x2 + r.w > l) { loc2 = r.w - (l - x2); if(x1 + loc2 < l) loc2 = -1; } if(loc1 == -1 && loc2 == -1) { continue; } else if(loc1 == -1) { ans++; } else if(loc2 == -1) { ans++; } else { if(loc1 == loc2) ans++; else ans += 2; } } System.out.println(ans); } int nextInt() { try { int c = System.in.read(); if (c == -1) return c; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return c; } if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } long nextLong() { try { int c = System.in.read(); if (c == -1) return -1; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return -1; } if (c == '-') return -nextLong(); long res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } String nextLine() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (c == '\r' || c == '\n') c = System.in.read(); do { res.append((char) c); c = System.in.read(); } while (c != '\r' && c != '\n'); return res.toString(); } catch (Exception e) { return null; } } public static void main(String[] args) { new TaskD().run(); } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
79012cadcdd61d7307c31f663b30f072
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { BufferedReader in; StringTokenizer st; PrintWriter out; int n, m, s; int[][] edge; ArrayList<Integer>[] g, cost; static class Pair implements Comparable<Pair> { int cost, v; public Pair(int cost, int v) { super(); this.cost = cost; this.v = v; } @Override public int compareTo(Pair o) { if (cost == o.cost) return v - o.v; return cost - o.cost; } } PriorityQueue<Pair> q = new PriorityQueue<Main.Pair>(); boolean[] was; int[] d; void Dijkstra(int v) { was = new boolean[n]; d = new int[n]; Arrays.fill(d, 1 << 29); d[v] = 0; for (q.add(new Pair(0, v)); !q.isEmpty();) { Pair p = q.poll(); v = p.v; int c = p.cost; if (was[v]) continue; was[v] = true; for (int i = 0; i < g[v].size(); ++i) { int u = g[v].get(i); int cost = this.cost[v].get(i); if (d[u] > c + cost) { d[u] = c + cost; q.add(new Pair(d[u], u)); } } } } void solve() throws IOException { n = ni(); m = ni(); s = ni() - 1; edge = new int[3][m]; g = new ArrayList[n]; cost = new ArrayList[n]; for (int i = 0; i < g.length; i++) { g[i] = new ArrayList<Integer>(); cost[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; ++i) { int v = ni() - 1; int u = ni() - 1; int c = ni(); g[v].add(u); g[u].add(v); cost[v].add(c); cost[u].add(c); edge[0][i] = v; edge[1][i] = u; edge[2][i] = c; } int l = ni(); Dijkstra(s); int ret = 0; for (int i = 0; i < n; ++i) if (d[i] == l) ++ret; // System.err.println(Arrays.toString(d)); for (int i = 0; i < m; ++i) { int v = edge[0][i]; int u = edge[1][i]; int c = edge[2][i]; if (d[u] == d[v] + c || d[v] == d[u] + c) { int min = min(d[u], d[v]); int max = max(d[u], d[v]); if (min < l && max > l) ++ret; } else { if (l > d[u] && d[u] + c > l && l <= d[v] + (d[u] + c - l)) ++ret; if (l > d[v] && d[v] + c > l && l <= d[u] + (d[v] + c - l)) { ++ret; if (2 * l == d[u] + d[v] + c) --ret; } } } out.println(ret); } public Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Main(); } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
76c7a8914fd8e8c7ee178ba2330d9fe7
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.Scanner; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; public class D103 { static Scanner in = new Scanner(System.in); static PrintWriter w = new PrintWriter(System.out, true); static int ni() { return in.nextInt(); } static String nl() { return in.nextLine(); } static void pl(int v) { w.println(v); } static void pl(String s) { w.println(s); } public static void shortestPaths(List<E>[] edges, int s, int[] prio, int[] pred) { Arrays.fill(pred, -1); Arrays.fill(prio, Integer.MAX_VALUE); prio[s] = 0; Queue<P> q = new PriorityQueue<P>(); q.add(new P(0, s)); while (!q.isEmpty()) { P cur = q.poll(); if (cur.p != prio[cur.v]) continue; for (E e : edges[cur.v]) { int v = e.v; int nprio = prio[cur.v] + e.c; if (prio[v] > nprio) { prio[v] = nprio; pred[v] = cur.v; q.add(new P(nprio, v)); } } } } public static void main(String[] args) { int n =ni(), m = ni(), s = ni(); List<E>[] nei = new ArrayList[n+1]; for (int i = 0; i < n + 1; i++) { nei[i] = new ArrayList<E>(); } final int[] prio = new int[n+1], pred = new int[n+1]; int[] v1 = new int[m], v2 = new int[m], w = new int[m]; for (int i = 0; i < m; i++) { v1[i] = ni(); v2[i] = ni(); w[i] = ni(); nei[v1[i]].add(new E(w[i], v2[i])); nei[v2[i]].add(new E(w[i], v1[i])); } int l = ni(); shortestPaths(nei, s, prio, pred); int sc = 0; for (int i = 1; i <= n; i++) { if (prio[i]==l) sc++; } for (int i = 0; i < m; i++) { if (prio[v1[i]] < l || prio[v2[i]] < l) { int l1 = l - prio[v1[i]]; int l2 = l - prio[v2[i]]; if (prio[v1[i]] >= l) { if (w[i]>l2) sc++; } else if (prio[v2[i]] >= l) { if (w[i]>l1) sc++; } else { if (l1+l2==w[i])sc++; else if (l1+l2<w[i]) sc+=2; } } } pl(sc); } static class E { int c; int v; public E(int cc, int vv) { c = cc; v = vv; } } static class P implements Comparable<P> { int p; int v; public P(int pp, int vv) { p = pp; v = vv; } public int compareTo(P o) { return p < o.p ? -1 : p > o.p ? 1 : 0; } } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
20773974bdd4093ff41c7b5eb69de469
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import static java.lang.Math.*; public class P144D { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int s = in.nextInt()-1; ArrayList<List<Point>> E = new ArrayList<List<Point>>(); for(int i=0; i<n; i++) E.add(new ArrayList<Point>()); for(int i=0; i<m; i++) { int x = in.nextInt()-1; int y = in.nextInt()-1; int d = in.nextInt(); E.get(x).add(new Point(y,d)); E.get(y).add(new Point(x,d)); } long L = in.nextInt(); if(L == 0) { System.out.println(1); return; } Set<Integer> S = new HashSet<Integer>(); TreeSet<Triple> Q = new TreeSet<Triple>(new Comparator<Triple>() { public int compare(Triple a, Triple b) { if(a.z != b.z) return a.z > b.z ? 1 : -1; if(a.y != b.y) return a.y > b.y ? 1 : -1; if(a.x == b.x) return 0; return a.x > b.x ? 1 : -1; } }); Q.add(new Triple(s,s,0)); long[] d = new long[n]; for(int i=0; i<n; i++) d[i] = -1; int[] P = new int[n]; d[s] = 0; while(!Q.isEmpty()) { Triple p = Q.pollFirst(); if(S.contains((int)p.x)) continue; S.add((int)p.x); d[(int)p.x] = p.z; P[(int)p.x] = (int)p.y; for(Point q:E.get((int)p.x)) { if(q.x == P[(int)p.x]) continue; if(d[q.x] == -1) { Q.add(new Triple(q.x, p.x, p.z+q.y)); } } } int ans = 0; Set<Integer> U = new HashSet<Integer>(); Set<Triple> X = new TreeSet<Triple>(new Comparator<Triple>() { public int compare(Triple a, Triple b) { if(a.z != b.z) return a.z > b.z ? 1 : -1; if(a.y != b.y) return a.y > b.y ? 1 : -1; if(a.x == b.x) return 0; return a.x > b.x ? 1 : -1; } }); //System.out.println(Arrays.toString(d)); for(int i=0; i<n; i++) { if(d[i] == L) { ans++; // System.out.println(i); } for(Point q:E.get(i)) { if(q.x == P[i]) continue; if(d[i] < L && d[i]+q.y > L) { long along = L - d[i]; if(q.y - along + d[q.x] < L) continue; if(q.y - along + d[q.x] == L && q.x < i) continue; ans++; // System.out.println(i+" "+q); } } } System.out.println(ans); } static class Triple { long x; long y; long z; public Triple(long x,long y, long z) { this.x = x; this.y = y; this.z = z; } public boolean equals(Object o) { if(!(o instanceof Object)) return false; Triple t = (Triple)o; return x==t.x && y==t.y && z==t.z; } public String toString() { return x+" "+y+" "+z; } } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
38a5dfcc748f2782c3160ee3e575fecb
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.lang.*; import java.awt.geom.Line2D; import java.io.*; import java.util.*; import java.math.*; public class D implements Runnable{ class V implements Comparable<V> { int dist, num; public V (int num, int dist) { this.num = num; this.dist = dist; } public int compareTo(V a) { return (this.dist==a.dist)?(this.num-a.num):(this.dist-a.dist); } } ArrayList<Integer>[] g, c; public void run() { int n = nextInt(); int m = nextInt(); int s = nextInt() - 1; g = new ArrayList[n]; c = new ArrayList[n]; for (int i = 0; i < n; ++i) { g[i] = new ArrayList<Integer>(); c[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; ++i) { int a = nextInt() - 1; int b = nextInt() - 1; int cc = nextInt(); g[a].add(b); g[b].add(a); c[a].add(cc); c[b].add(cc); } int INF = Integer.MAX_VALUE/3; int[] dist = new int[n]; int[] prev = new int[n]; Arrays.fill(prev, -1); Arrays.fill(dist, INF); dist[s] = 0; TreeSet<V> set = new TreeSet<V>(); set.add(new V(s,0)); while(set.size() > 0) { V v = set.pollFirst(); for (int i = 0; i < g[v.num].size(); ++i) { int to = g[v.num].get(i); int cost = c[v.num].get(i); if (dist[to] > dist[v.num] + cost) { dist[to] = dist[v.num] + cost; set.add(new V(to, dist[to])); } } } int l = nextInt(); int ans = 0; for (int i = 0; i < n; ++i) { if (dist[i] == l) { ++ans; // out.println(i); } for (int j = 0; j < g[i].size(); ++j) { int to = g[i].get(j); int cost = c[i].get(j); if (dist[i] < l && dist[i] + cost > l) { int diff = cost - (l - dist[i]); if (l < dist[to] + diff) { ++ans; // out.println(i + " " + to); } else if (l == dist[to] + diff && i < to) { ++ans; // out.println(i + " " + to); } } } } out.println(ans); out.flush(); } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new D())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
c6663e8b02b1330ef61038c602078d5c
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.PriorityQueue; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.Collection; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Queue; import java.math.BigInteger; import java.util.Collections; 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; StreamInputReader in = new StreamInputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, StreamInputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), s = in.readInt(); Node[] nodes = new Node[n + 1]; for (int i = 0; i < n; ++i) { nodes[i + 1] = new Node(i + 1); } Edge[] edges = new Edge[m]; for (int i = 0; i < m; ++i) { int u = in.readInt(), v = in.readInt(), w = in.readInt(); edges[i] = new Edge(u, v, w); nodes[u].adj.add(new Edge(u, v, w)); nodes[v].adj.add(new Edge(v, u, w)); } int L = in.readInt(); for (int i = 1; i <= n; ++i) { Collections.sort(nodes[i].adj); } final long[] dis = new long[n + 1]; Arrays.fill(dis, Long.MAX_VALUE / 3); dis[s] = 0; Queue<Node> q = new PriorityQueue<Node>(); q.add(nodes[s]); int res = 0; boolean[] vis = new boolean[n + 1]; while (q.size() > 0) { Node node = q.poll(); if (vis[node.v]) { continue; } vis[node.v] = true; if (dis[node.v] == L) { ++res; } for (Edge edge : node.adj) { if (dis[edge.to] > dis[node.v] + edge.len) { dis[edge.to] = dis[node.v] + edge.len; Node nd = new Node(nodes[edge.to]); nd.dis = dis[edge.to]; q.add(nd); } } } for(Edge edge: edges) { long uDis = dis[edge.from], vDis = dis[edge.to]; if (uDis < L && vDis > L || uDis > L && vDis < L) ++res; else if (uDis < L || vDis < L) { long d = 2 * L - uDis - vDis; boolean f = uDis < L && vDis < L; if (d < edge.len) { res += f ? 2 : 1; } else if (d == edge.len) { res += f ? 1 : 0; } } /*long a = -1, b = -1; if (uDis < L) { a = L - uDis; } if (vDis < L) { b = L - vDis; } int add = 0; if (a > 0 && a < edge.len) { ++add; } if (b > 0 && b < edge.len) { ++add; } if (a + b >= edge.len && add == 2) { --add; } res += add;*/ } out.printLine(res); } class Node implements Comparable<Node> { public int v; public List<Edge> adj; public long dis; public Node(Node node) { this.v = node.v; this.adj = node.adj; this.dis = node.dis; } public Node(int v) { this.v = v; this.adj = new ArrayList<Edge>(); } public int compareTo(Node o) { return IntegerUtils.longCompare(dis, o.dis); } } class Edge implements Comparable<Edge> { public int from, to; public long len; public Edge(int from, int to, int len) { this.from = from; this.to = to; this.len = len; } public int compareTo(Edge o) { if (len < o.len) { return -1; } if (len > o.len) { return 1; } return 0; } } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public StreamInputReader(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++]; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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(); } } abstract class InputReader { public abstract int read(); 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; } protected boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class IntegerUtils { public static int longCompare(long a, long b) { if (a < b) return -1; if (a > b) return 1; return 0; } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
5cd7b9e14c3d2f3de57aa5d9dcca5207
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.util.PriorityQueue; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.Collection; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Queue; import java.math.BigInteger; import java.util.Collections; 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; StreamInputReader in = new StreamInputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, StreamInputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), s = in.readInt(); Node[] nodes = new Node[n + 1]; for (int i = 0; i < n; ++i) { nodes[i + 1] = new Node(i + 1); } Edge[] edges = new Edge[m]; for (int i = 0; i < m; ++i) { int u = in.readInt(), v = in.readInt(), w = in.readInt(); edges[i] = new Edge(u, v, w); nodes[u].adj.add(new Edge(u, v, w)); nodes[v].adj.add(new Edge(v, u, w)); } int L = in.readInt(); for (int i = 1; i <= n; ++i) { Collections.sort(nodes[i].adj); } final long[] dis = new long[n + 1]; Arrays.fill(dis, Long.MAX_VALUE / 3); dis[s] = 0; Queue<Node> q = new PriorityQueue<Node>(); q.add(nodes[s]); int res = 0; boolean[] vis = new boolean[n + 1]; while (q.size() > 0) { Node node = q.poll(); if (vis[node.v]) { continue; } vis[node.v] = true; if (dis[node.v] == L) { ++res; } for (Edge edge : node.adj) { if (dis[edge.to] > dis[node.v] + edge.len) { dis[edge.to] = dis[node.v] + edge.len; Node nd = new Node(nodes[edge.to]); nd.dis = dis[edge.to]; q.add(nd); } } } for(Edge edge: edges) { long uDis = dis[edge.from], vDis = dis[edge.to]; if (uDis > vDis) { long t = uDis; uDis = vDis; vDis = t; } if (vDis <= L && uDis + edge.len == vDis) { continue; } if (vDis > L && uDis < L) { ++res; continue; } long a = L - uDis, b = L - vDis; if (a + b == edge.len) { ++res; } else if (a + b > 0 && a + b < edge.len) { if (a > 0) ++res; if (b > 0) ++res; } } out.printLine(res); } class Node implements Comparable<Node> { public int v; public List<Edge> adj; public long dis; public Node(Node node) { this.v = node.v; this.adj = node.adj; this.dis = node.dis; } public Node(int v) { this.v = v; this.adj = new ArrayList<Edge>(); } public int compareTo(Node o) { return IntegerUtils.longCompare(dis, o.dis); } } class Edge implements Comparable<Edge> { public int from, to; public long len; public Edge(int from, int to, int len) { this.from = from; this.to = to; this.len = len; } public int compareTo(Edge o) { if (len < o.len) { return -1; } if (len > o.len) { return 1; } return 0; } } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public StreamInputReader(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++]; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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(); } } abstract class InputReader { public abstract int read(); 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; } protected boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class IntegerUtils { public static int longCompare(long a, long b) { if (a < b) return -1; if (a > b) return 1; return 0; } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
standard output