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
b73bd0a386b8cca0f70e6a33439ce75d
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int best = -50 * 100; int n = sc.nextInt(); String bestName = ""; while (n-- > 0) { String name = sc.next(); int score = sc.nextInt() * 100 - sc.nextInt() * 50 + sc.nextInt() + sc.nextInt() + sc.nextInt() + sc.nextInt() + sc.nextInt(); if (score > best) { best = score; bestName = name; } } out.println(bestName); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner (FileReader f) {br = new BufferedReader(f);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
78cdcbb2d1a41b9cf806724bb783a466
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { String lName = ""; int lScore = Integer.MIN_VALUE; int n = in.nextInt(); for (int i = 0; i < n; i++) { String name = in.next(); int score = 100 * in.nextInt(); score -= 50 * in.nextInt(); score += in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt(); if (score > lScore) { lScore = score; lName = name; } } out.println(lName); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
e0ee847ba0f7477cd1cacf95b43567df
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class SolutionB { public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //Map<String, Integer> map = new HashMap<String, Integer>(); int max = Integer.MIN_VALUE; String leader = ""; for(int i = 0; i < n; i++){ String h = sc.next(); //map.put(h, 0); int score = 0; score += (100 * sc.nextInt()); score -= (50 * sc.nextInt()); for(int j = 0; j < 5; j++){ score += sc.nextInt(); } if(max < score){ max = score; leader = h; } // map.put(h, score); } System.out.println(leader); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
4b0ce9b7a47dbd985f0c33238b1000f3
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws IOException { new A().run(); } FastScanner in; PrintWriter out; void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, true); solve(); out.close(); } void solve() throws IOException { int maxScore = Integer.MIN_VALUE; String winner = new String(); int n = in.nextInt(); for (int i = 0; i < n; i++) { String name = in.next(); int sum = 100 * in.nextInt(); sum -= 50 * in.nextInt(); for (int j = 0; j < 5; j++) sum += in.nextInt(); if (sum > maxScore) { maxScore = sum; winner = new String(name); } //System.err.println(sum); } out.println(winner); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
d96f31d691c022d9f30c5acd45d69099
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; public class A{ public static class Contestant implements Comparable<Contestant>{ String name; int points; public Contestant(String s, int p){ name = s; points = p; } public int compareTo(Contestant other){ return points - other.points; } } public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); ArrayList<Contestant> board = new ArrayList<>(); for (int i = 0; i < n; i++){ String name = s.next(); int score = 0; score += 100 * s.nextInt(); score -= 50 * s.nextInt(); for (int j = 0; j < 5; j++){ score += s.nextInt(); } Contestant c = new Contestant(name, score); board.add(c); } Collections.sort(board); System.out.println(board.get(board.size() - 1).name); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
64d6bce78415bc32e56a89648855f44c
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Set; import java.util.StringTokenizer; public class RoomLeader { public static void main(String[] args) { PrintWriter pw = new PrintWriter(System.out); reader(System.in); int n = nI(); HashMap <String, Integer> hashMap = new HashMap <String, Integer> (); int sum = 0; int t = 0; for (int i = 0; i < n; i++) { String s = n(); for (int j = 0; j < 7; j++) { t = nI(); if (j == 0) { sum += t * 100; } else if (j == 1) { sum -= t * 50; } else { sum += t; } } hashMap.put(s, sum); sum = 0; } int max = Integer.MIN_VALUE; String ans = ""; for (String key : hashMap.keySet()) { if (max < hashMap.get(key)) { ans = key; max = hashMap.get(key); } } pw.println(ans); pw.close(); } private static BufferedReader br; private static StringTokenizer st; static void reader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } static String n() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nI() { return Integer.parseInt(n()); } static long nL() { return Long.parseLong(n()); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
f814b4da6a7bda137bb8c0e405a2e300
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class a74 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int tc=sc.nextInt(); int su[]=new int[tc]; String s[]=new String[tc]; int x=0; for(int i=0;i<tc;i++) { int sum=0; s[i]=sc.next(); int a[]=new int[7]; for(int j=0;j<7;j++) a[j]=sc.nextInt(); sum+=(a[0]*100)-(a[1]*50)+a[2]+a[3]+a[4]+a[5]+a[6]; su[x++]=sum; } int max=su[0],y=0; for(int j=1;j<tc;j++) if(max<su[j]) { max=su[j]; y=j; } System.out.println(s[y]); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
f21254416ce03537869af2ade235baba
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); String win=new String(); int res=Integer.MIN_VALUE; for(int i=0;i<n;i++){ String t=sc.next(); int temp=sc.nextInt()*100-sc.nextInt()*50+sc.nextInt()+sc.nextInt() +sc.nextInt()+sc.nextInt()+sc.nextInt(); if(temp>res){ res=temp; win=t; } } System.out.println(win); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
05ee78f3df940f6c2693f2d1b7538dd5
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class Main { class Node{ int value, nuOfC=0, done=0; List<Integer> connections; public Node(){ connections = new ArrayList<Integer>(); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public int getNuOfC() { return nuOfC; } public void setNuOfC(int nuOfC) { this.nuOfC = nuOfC; } public List<Integer> getConnections() { return connections; } public void setConnections(List<Integer> connections) { this.connections = connections; } } class Net{ HashMap <Integer, Node> map; public Net(){ map = new HashMap <Integer, Node>(); } public void addNode(int val){ Node node= new Node(); node.setValue(val); map.put(val, node); } public void editNode(int from, int to) { Node node = map.get(from); node.nuOfC++; node.connections.add(to); map.replace(from, node); } public int getMax() { int ret = 1; while (true){ int max=-1111, idx = -1; for (int i = 0;i<=map.size();i++){ if (map.containsKey(i) && map.get(i).nuOfC > max && map.get(i).done == 0){ max = map.get(i).nuOfC; idx = i; } } System.out.println(idx); if (idx == -1) break; List<Integer> list = map.get(idx).connections; Node nn = map.get(idx); nn.done = 1; map.replace(idx, nn); for (int i = 0 ; i < map.get(idx).nuOfC ; i++){ ret*=2; } HashMap <Integer, Node> map1 = new HashMap <Integer, Node>(); for (int i = 0 ; i < list.size() ; i++){ Node nod = map.get(list.get(i)); if (nod!=null && nod.done==0){ nod.nuOfC--; map1.put(list.get(i), nod); } } map = map1; } return ret; } } private static int doIt(int i, int j, int res) { System.out.println(i + " " + j + " " + res); if (i == j) return res; if (i<=0 || j<=0) return -1; if (i %2==0){ if (j%2==0){ doIt(i, j/2,res+1); doIt(i/2, j/2,res+1); } if (j%3==0){ doIt(i, j/3,res+1); doIt(i/2, j/3,res+1); } if (j%5==0){ doIt(i, j/5,res+1); doIt(i/2, j/5,res+1); } } if (i %3==0){ if (j%2==0){ doIt(i, j/2,res+1); doIt(i/3, j/2,res+1); } if (j%3==0){ doIt(i, j/3,res+1); doIt(i/3, j/3,res+1); } if (j%5==0){ doIt(i, j/5,res+1); doIt(i/3, j/5,res+1); } }if (i %5==0){ if (j%2==0){ doIt(i, j/2,res+1); doIt(i/5, j/2,res+1); } if (j%3==0){ doIt(i, j/3,res+1); doIt(i/5, j/3,res+1); } if (j%5==0){ doIt(i, j/5,res+1); doIt(i/5, j/5,res+1); } } return -54; } public static void main(String[] args) { Scanner in = new Scanner(System.in); //System.out.println(doIt(15, 20,0 )); //74 int n = in.nextInt(); int max = -11111; String ret = ""; for (int i=0; i < n ; i++){ String name = in.next(); int plus = in.nextInt(); int minus = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int d = in.nextInt(); int e = in.nextInt(); int res = (100*plus)-(50*minus)+a+b+c+d+e; if (res>max){ max = res; ret = name; } } System.out.println(ret); /* //9C String n = in.next(); int x=0; for (int i = 0 ; i < n.length();i++) if (n.charAt(i)=='1' || n.charAt(i)=='0') x++; System.out.println(x); */ /* // 416A int n = in.nextInt(); int ret = 0; for (int i = 0 ; i < n;i++){ String sym = in.next(), va = in.next(), ans = in.next(); if (sym.equals(">") && ans.equals("Y")){ ret = Integer.parseInt(va)+1; } if (sym.equals(">") && ans.equals("N")){ ret = Integer.parseInt(va)-1; } } */ /* // 5A String h; int l = 0; int alive =0; while((h = in.nextLine()) != null){ if (h.charAt(0) == '+'){ alive++; } else if (h.charAt(0) == '-'){ alive--; }else{ int idx = h.indexOf(':'); int msg = ((int)h.length()) - idx-1; l += (msg*alive); } } System.out.println(l); */ /* // 445B int n = in.nextInt(), m = in.nextInt(); int [] arr= new int[n+1]; int ret = (int)Math.pow(2, n-1); for (int i = 1 ; i <=m ;i++){ int e = in.nextInt(), g = in.nextInt(); arr[e] = 1; arr[g] = 1; } int cou = 0; for (int i = 1 ; i <= n ; i++){ if (arr[i] != 1) cou++; } if (m!=0) for (int i = 0 ; i < cou ; i ++) ret/=2; System.out.println(ret); */ /* // string n; int k; cin >> n >> k; for (int i = 0 ; i < n.size()-1 ; i++){ if (n[i] < n[i+1] && k>0){ char h = n[i]; n[i] = n[i+1]; n[i+1] = h; k--; for (int j = i ; j > 0 ; j--){ if (n[j] > n[j-1] && k>0){ char h = n[j]; n[j] = n[j-1]; n[j-1] = h; k--; } } } if (k==0) break; } cout << n;*/ /* // 584C int n= in.nextInt(), m= in.nextInt(); String s1 = in.next(), s2 = in.next(); int same = 0; for (int i = 0 ; i < n ; i++){ if (s1.charAt(i) == s2.charAt(i)){ same++; } } if (same <= m ){ System.out.println(-1); System.exit(0); } */ /* int w = in.nextInt(), h = in.nextInt(), n = in.nextInt(); int arrw[] = new int[200001]; int arrh[] = new int[200001]; arrw[0]=1; arrh[0]=1; for (int i = 0 ; i < 4 ; i++){ String dir = in.next(); int num = in.nextInt(); System.out.println(dir+" "+num); if (dir.equals("H")){ arrw[num] = 1; }else{ arrh[num] = 1; } int maxw=-1231233,maxh=-1212121; int id = -1,idx=-1; for (int p = 0 ; p < 200001;p++){ if (arrw[p]==1){ if (id !=-1){ maxw = Math.max(maxw, p-id); } id = p; } if (arrh[p]==1){ if (idx !=-1){ maxh = Math.max(maxh,p-idx); } idx = p; } } System.out.println(maxh * maxw); } */ /* // 614/B int n ; n = in.nextInt(); BigInteger z = new BigInteger("10"); String h = "";String ret = ""; for (int j = 0 ;j < n ; j++){ h += in.next(); h+= " "; } Scanner im = new Scanner(h); int ind= 0; while(im.hasNext()){ BigInteger g = new BigInteger(im.next()); BigInteger y =z.pow(g.toString().length()-1); if (g.subtract(y).compareTo( BigInteger.ZERO ) == 1){ System.out.print(g); String q = g.toString(); for (int o = q.length()-1 ; o >=0 ; o--){ if (q.charAt(o) == '0'){ ind++; } if (q.charAt(o) != '0'){ break; } } break; } } im.close(); int ones = 1; for (int i = h.length()-1 ; i>=0 ; i--){ if (h.charAt(i) != '0'){ ones=0; } if (h.charAt(i) == ' '){ ones = 1; } if (h.charAt(i) == '0' && ones == 1 && i !=0 && h.charAt(i-1) != ' '){ ret+='0'; } if ( (h.charAt(i) == '0' && ones == 1 && i == 0) || (h.charAt(i) == '0' && ones == 1 && i != 0 && h.charAt(i-1) == ' ') ){ System.out.println(0); in.close(); System.exit(0); } } System.out.println(ret.substring(0,ret.length()-ind)); */ in.close(); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
091b9882017e3b4efa0688399d20aa70
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { FastReader in=new FastReader(); int n=in.nextInt(); String[]x=new String[n]; int y=0; long max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { long count=0; String s=in.next(); x[i]=s; int plus=in.nextInt(),minus=in.nextInt(); int a=in.nextInt(),b=in.nextInt(),c=in.nextInt(),d=in.nextInt(),e=in.nextInt(); plus*=100; minus*=50; plus-=minus; count+=(long)a+b+c+d+e+plus; if(count>max) { max=count; y=i; } } System.out.println(x[y]); } } 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
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
b6a8913bf6cb530c117a6152528dff04
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] arr = new String[n]; String w =""; int sum =0; for ( int i = 0 ; i < n ; i++ ){ arr[i] = sc.next(); int plus = sc.nextInt(); int minus = sc.nextInt(); int A = sc.nextInt(); int b = sc.nextInt(); int C = sc.nextInt(); int D = sc.nextInt(); int E = sc.nextInt(); if ( plus > 50 ) { plus = 50; } if ( minus > 50 ) { minus = 50; } if ( A < 150 || A > 500 ) { A = 0; } if ( b < 300 || b > 1000 ) { b = 0; } if ( C < 450 || C > 1500 ) { C = 0 ;} if ( D < 600 || D > 2000 ) { D = 0; } if ( E < 750 || E > 2500 ) { E = 0; } int z = A + b + C + D + E + (plus*100 - minus*50); if ( i == 0 ) { sum = z; w = arr[i];} else if ( z > sum ) { sum = z; w = arr[i]; } } System.out.println(w); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
71746963fe6dcd64e029015e1256941b
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Pair<Integer, String>[] mem = new Pair[n]; for (int i = 0; i < n; i++) { int cur = 0; String name = in.next(); cur = in.readInt()*100; cur -= in.readInt()*50; for (int j = 0; j < 5; j++) cur += in.readInt(); mem[i] = Pair.makePair(cur, name); } Arrays.sort(mem); out.print(mem[n - 1].second); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { 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 { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static<U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>)first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>)second).compareTo(o.second); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
485d32b5e35791c8236407fae9c3c7e3
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { public static BufferedReader in; public static PrintWriter out; public static StringTokenizer tok; public static void main(String args[]) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); //in = new BufferedReader(new FileReader("in.txt")); //out = new PrintWriter(new FileWriter("out.txt")); solve(); in.close(); out.close(); } static void solve() throws IOException { ArrayList < contestent > list = new ArrayList<>(); String name; int[] value = new int[8]; int n; n = nextInt(); while( n > 0 ) { --n; name = next(); for(int i=0; i<7; i++) { value[ i ] = nextInt(); } list.add( new contestent( name, value ) ); } Collections.sort( list ); out.println( list.get( 0 ) ); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static String nextLine() throws IOException { tok = new StringTokenizer(""); return in.readLine(); } public static boolean hasNext() throws IOException { while (tok == null || !tok.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return false; } tok = new StringTokenizer(s); } return true; } } class contestent implements Comparable < contestent > { private String name; private int val; public contestent(String name,int[] values) { this.name = name; val = values[ 0 ] * 100; val -= values[ 1 ] * 50; for(int i=2; i<7; i++) { val += values[ i ]; } } public int compareTo(contestent other) { return Integer.compare( -val, -other.val ); } public String toString() { return name; } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
af08b78959fc6471457bc5e70860efe5
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class Codes { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int number = input.nextInt(); String roomLeader = new String(); int maxScore = Integer.MIN_VALUE; for (int i = 0; i < number; i++) { int sum = 0; String handle = input.next(); for (int j = 0; j < 7; j++) { if (j != 1 && j != 0) { sum+=input.nextInt(); } else if(j != 1) { sum+=(input.nextInt()*100); } else { sum-=(input.nextInt()*50); } } if(sum > maxScore) { maxScore = sum; roomLeader = handle; } } System.out.println(roomLeader); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
da87661b188579f6fe7814bacfb94395
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class SuperLukeyNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int max = 0; String maxHandler = ""; int n = scanner.nextInt(); for (int i = 0; i < n; i++) { String temp = scanner.next(); int r = 0; int temps = scanner.nextInt(); r+= 100 * temps; temps = scanner.nextInt(); r+= -50 * temps; temps = scanner.nextInt(); r+= temps; temps = scanner.nextInt(); r+= temps; temps = scanner.nextInt(); r+= temps; temps = scanner.nextInt(); r+= temps; temps = scanner.nextInt(); r+= temps; if ( i == 0 || r > max){ max = r; maxHandler = temp; } } System.out.println(maxHandler); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
21f647a2196457bd730f2e23ef1c4559
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.InputMismatchException; import java.util.TreeMap; import java.util.TreeSet; public class Tester { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n=ni(),max=-999999999; String w=""; for(int i=0;i<n;i++) { String s=ns(); int t=100*ni()-50*ni()+ni()+ni()+ni()+ni()+ni(); if(t>max) { max=t; w=s; } } out.println(w); } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } 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 Tester().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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
06d69e204a35e38a9137c23a33170ad3
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.Closeable; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class A implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); A() throws IOException { // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter(new FileWriter("output.txt")); } StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, int k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } int inv(int x) { return pow(x, MOD - 2); } void solve() throws IOException { int n = nextInt(); String[] handles = new String[n]; int[] scores = new int[n]; int[] f = {100, -50, 1, 1, 1, 1, 1}; for (int i = 0; i < n; i++) { handles[i] = next(); for (int x : f) { scores[i] += x * nextInt(); } } int li = 0; for(int i = 0; i < n; i++) { if(scores[i] > scores[li]) { li = i; } } writer.println(handles[li]); } public static void main(String[] args) throws IOException { try (A a = new A()) { a.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
472804468915c6ecbcdd4f9a19f104e3
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RoomLeader { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); int max=Integer.MIN_VALUE; String leader=""; for(int i=0;i<t;i++){ int score=0; String s[]=br.readLine().split(" "); score=(Integer.parseInt(s[3]))+(Integer.parseInt(s[4]))+(Integer.parseInt(s[5]))+(Integer.parseInt(s[6]))+(Integer.parseInt(s[7])); score+=(Integer.parseInt(s[1]))*100; score-=(Integer.parseInt(s[2]))*50; if(score>max){ max=score; leader=s[0]; } } System.out.println(leader); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
ac8aba9787620adb7e18a1bf92d62743
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; public class Sr { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); String[]arr=new String[n]; int[]p=new int[7]; int[]s=new int[n]; int[]s2=new int[n]; for (int i = 0; i < n; i++) { int sum=0; arr[i]=in.next(); for (int j = 0; j <7; j++) { p[j]=in.nextInt(); if(j>1) sum+=p[j]; } sum+=(p[0]*100-p[1]*50); s[i]=sum; s2[i]=sum; } Arrays.sort(s); for (int i = 0; i < n; i++) { if(s[s.length-1]==s2[i]) System.out.println(arr[i]); } } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
90a92a3b5f9d9fa497cac339eb2b0ac7
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class RoomLeader { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); String [] part = new String[n]; int[]plus = new int[n], minus = new int[n],a= new int [n], b =new int[n], c =new int[n], d =new int[n], e= new int[n];int [] score = new int[n]; int max = (int)(1e9) *-1; String s = ""; for (int i = 0; i < n; i++) { String str = sc.nextLine(); StringTokenizer st = new StringTokenizer(str, " "); part[i] = st.nextToken(); plus[i] = Integer.parseInt(st.nextToken())*100; minus[i] = Integer.parseInt(st.nextToken())*-50; a[i] = Integer.parseInt(st.nextToken()); b[i] = Integer.parseInt(st.nextToken()); c[i] = Integer.parseInt(st.nextToken()); d[i] = Integer.parseInt(st.nextToken()); e[i] = Integer.parseInt(st.nextToken()); score[i] = plus[i] + minus[i] + a[i] + b[i] + c[i] + d[i] + e[i]; // max = Math.max(max, score[i]); if(max < score[i]){ s= part[i]; max = score[i]; } } out.println(s); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public boolean ready() throws IOException { return br.ready(); } public String nextLine() throws IOException {return br.readLine();} } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
a6dc7d96d03f7b9cc1b987c0c32f7550
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class A74 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); String answer = null; int maxPoints = Integer.MIN_VALUE; for (int n=0; n<N; n++) { String name = in.next(); int plus = in.nextInt(); int minus = in.nextInt(); int points = 100*plus - 50*minus; for (int i=0; i<5; i++) { points += in.nextInt(); } if (points > maxPoints) { maxPoints = points; answer = name; } } System.out.println(answer); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
e0356ebf1c5ae2b877d8ca5afb8ef749
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class A_Rooms { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); int gamersCount = Integer.parseInt(line); String winner = ""; int winnerScore = Integer.MIN_VALUE; for (int i = 0; i < gamersCount; i++) { String raw = scanner.nextLine(); String[] gamerScore = raw.trim().split(" "); int gamerPoints = Integer.parseInt(gamerScore[1]) * 100 - Integer.parseInt(gamerScore[2]) * 50 + Integer.parseInt(gamerScore[3]) + Integer.parseInt(gamerScore[4]) + Integer.parseInt(gamerScore[5]) + Integer.parseInt(gamerScore[6]) + Integer.parseInt(gamerScore[7]); if (gamerPoints > winnerScore) { winnerScore = gamerPoints; winner = gamerScore[0]; } } System.out.println(winner); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
1e495390f975f088ad489a6496b18e0d
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Arrays; public class long2{ static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //Fastscanner class end static FastScanner in=new FastScanner(); static PrintWriter ww=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String args[])throws IOException { //Main ob=new Main(); long2 ob=new long2(); ob.solve(); ww.close(); } public void solve()throws IOException { int max=Integer.MIN_VALUE; int n=in.nextInt(); String res=new String(); for(int i=1;i<=n;i++) { String handle=in.nextString(); int plus=in.nextInt(); int minus=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); int c=in.nextInt(); int d=in.nextInt(); int e=in.nextInt(); int solve=plus*100-minus*50+a+b+c+d+e; if(solve>max) { max=solve; res=new String(handle); } } System.out.println(res); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
9ac67ad06881e84a7af01d6d3e0be5fb
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.io.BufferedReader; import java.io.InputStreamReader; public class RoomLeader74A { public static void main(final String[] args) throws Exception { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); final int n = Integer.parseInt(reader.readLine().trim()); final Contestant contestants[] = new Contestant[n]; for (int i = 0; i < n; i++) { final String contestantString[] = reader.readLine().trim().split("\\s+"); final String name = contestantString[0].trim(); final int successfulHacks = Integer.parseInt(contestantString[1].trim()); final int unsuccessfulHacks = Integer.parseInt(contestantString[2].trim()); final int scoreA = Integer.parseInt(contestantString[3].trim()); final int scoreB = Integer.parseInt(contestantString[4].trim()); final int scoreC = Integer.parseInt(contestantString[5].trim()); final int scoreD = Integer.parseInt(contestantString[6].trim()); final int scoreE = Integer.parseInt(contestantString[7].trim()); final Contestant contestant = new Contestant(name, successfulHacks, unsuccessfulHacks, scoreA, scoreB, scoreC, scoreD, scoreE); contestants[i] = contestant; } Arrays.sort(contestants, new Comparator<Contestant>() { public int compare(Contestant c1, Contestant c2) { return c2.totalScore - c1.totalScore; } }); System.out.println(contestants[0].name); } } class Contestant { String name; int totalScore; public Contestant(final String name, final int successfulHacks, final int unsuccessfulHacks, final int scoreA, final int scoreB, final int scoreC, final int scoreD, final int scoreE) { this.name = name; this.totalScore = 0; this.totalScore += successfulHacks * 100 + scoreA + scoreB + scoreC + scoreD + scoreE; this.totalScore -= unsuccessfulHacks * 50; } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
6a4f015ad032bf89db3a4e2710f38783
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; public class P74A { public static void main(String [] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String winner = ""; int winner_point = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { String handle = in.next(); int total = (in.nextInt() * 100) - (in.nextInt() * 50) + in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt(); if (total > winner_point) { winner_point = total; winner = handle; } } System.out.println(winner); in.close(); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
882c11d061fead376bd43b12a1fab201
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class RoomLeader { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int n = input.nextInt(); String s = ""; int max = Integer.MIN_VALUE; for(int i=0;i<n;i++){ String z = input.next(); int total = 100*input.nextInt(); total-=50*input.nextInt(); int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt(); int d = input.nextInt(); int e = input.nextInt(); total = total+a+b+c+d+e; if(total>max){ max = total; s = z; } } System.out.println(s); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
d1a2e082e08d4cf9637373d727b803ab
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.StringTokenizer; import javafx.util.converter.BigIntegerStringConverter; import java.util.*; /** * * @author Ahmad */ public class JavaApplication1 { public static void main (String[] args) throws IOException, Exception { FastReader console = new FastReader(); int n = console.nextInt() ; String ans = "" ; int max = Integer.MIN_VALUE ; for (int i=0 ; i<n ; i++){ String x = console.next() ; int sum = 0 ; int a = console.nextInt() ; int b = console.nextInt() ; sum+=(a*100) ; sum-=(b*50) ; for (int j=0 ; j<5 ; j++){ sum+=console.nextInt() ; } if (sum>max){ ans=x ; max=sum ; } } System.out.println(ans); } } class Sorting{ public static int[] bucketSort(int[] array, int bucketCount) { if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count"); if (array.length <= 1) return array; //trivially sorted int high = array[0]; int low = array[0]; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i] > high) high = array[i]; if (array[i] < low) low = array[i]; } double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket ArrayList<Integer> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array buckets[(int)((array[i] - low)/interval)].add(array[i]); } int pointer = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[pointer] = buckets[i].get(j); pointer++; } } return array; } } 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
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
ac8aed4b130ee96e81003deadbb3c744
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.*; /** * https://codeforces.com/problemset/problem/74/A */ public class Problem74A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); scanner.useDelimiter(System.lineSeparator()); int n = Integer.parseInt(scanner.next()); List<Pair<String, Long>> results = new ArrayList<>(n); for (int i = 0; i < n; i++) { String[] result = scanner.next().split(" "); long points = 100L * Long.parseLong(result[1]) - 50 * Long.parseLong(result[2]) + Long.parseLong(result[2]) + Long.parseLong(result[3]) + Long.parseLong(result[4]) + Long.parseLong(result[5]) + Long.parseLong(result[6]) + Long.parseLong(result[7]); Pair<String, Long> pair = new Pair<>(result[0], points); results.add(pair); } scanner.close(); Optional<Pair<String, Long>> max = results.stream().max(Comparator.comparing(Pair::getSecond)); System.out.println(max.get().getFirst()); } private static class Pair<T, V> { private T first; private V second; Pair(T first, V second) { this.first = first; this.second = second; } T getFirst() { return first; } V getSecond() { return second; } } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 8
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
13993a78f296b7e645dd6ef808794439
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.util.Scanner; public class A74 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String s; String s1 =""; int l =-100000000, n = sc.nextInt(), a = 0, b = 0, c = 0, d = 0, e = 0, p = 0, m = 0, result = 0; for (int i = 0; i < n; i ++) { s = sc.next(); p = sc.nextInt(); m = sc.nextInt(); a = sc.nextInt(); b = sc.nextInt(); c = sc.nextInt(); d = sc.nextInt(); e = sc.nextInt(); result = a + b + c + d + e+ p*100 - m*50; if (result > l) { l = result; s1 = s; } } System.out.print(s1); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 6
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
627b56458ac0c734b60c4de663017392
train_003.jsonl
1302879600
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String []s = new String[n]; int []score = new int[n]; for(int i=0;i<n;i++){ s[i] = in.next(); score[i] += in.nextInt()*100; score[i] -= in.nextInt()*50; for(int j=0;j<5;j++) score[i] += in.nextInt(); } int max =Integer.MIN_VALUE ; int index = 0; for(int i=0;i<n;i++) if(score[i]>max){ max = score[i]; index = i; } out.println(s[index]); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } }
Java
["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"]
2 seconds
["tourist"]
NoteThe number of points that each participant from the example earns, are as follows: Petr — 3860 tourist — 4140 Egor — 4030 c00lH4x0R —  - 350 some_participant — 2220 Thus, the leader of the room is tourist.
Java 6
standard input
[ "implementation" ]
b9dacff0cab78595296d697d22dce5d9
The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≤ plusi, minusi ≤ 50; 150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved; 300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved; 450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved; 600 ≤ di ≤ 2000 or di = 0, if problem D is not solved; 750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
1,000
Print on the single line the handle of the room leader.
standard output
PASSED
2e4bd648030782b8bf80a61d9bb36c6d
train_003.jsonl
1604327700
A permutation is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ — are permutations, and $$$[1, 1]$$$, $$$[4, 3, 1]$$$, $$$[2, 3, 4]$$$ — no.Permutation $$$a$$$ is lexicographically smaller than permutation $$$b$$$ (they have the same length $$$n$$$), if in the first index $$$i$$$ in which they differ, $$$a[i] &lt; b[i]$$$. For example, the permutation $$$[1, 3, 2, 4]$$$ is lexicographically smaller than the permutation $$$[1, 3, 4, 2]$$$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation $$$a$$$ of length $$$n$$$ — is the lexicographically smallest permutation $$$b$$$ of length $$$n$$$ that lexicographically larger than $$$a$$$. For example: for permutation $$$[2, 1, 4, 3]$$$ the next permutation is $$$[2, 3, 1, 4]$$$; for permutation $$$[1, 2, 3]$$$ the next permutation is $$$[1, 3, 2]$$$; for permutation $$$[2, 1]$$$ next permutation does not exist. You are given the number $$$n$$$ — the length of the initial permutation. The initial permutation has the form $$$a = [1, 2, \ldots, n]$$$. In other words, $$$a[i] = i$$$ ($$$1 \le i \le n$$$).You need to process $$$q$$$ queries of two types: $$$1$$$ $$$l$$$ $$$r$$$: query for the sum of all elements on the segment $$$[l, r]$$$. More formally, you need to find $$$a[l] + a[l + 1] + \ldots + a[r]$$$. $$$2$$$ $$$x$$$: $$$x$$$ times replace the current permutation with the next permutation. For example, if $$$x=2$$$ and the current permutation has the form $$$[1, 3, 4, 2]$$$, then we should perform such a chain of replacements $$$[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$$$. For each query of the $$$1$$$-st type output the required sum.
256 megabytes
import java.util.*; import java.io.*; public class codeforces { static long[]a; static long[]fac; public static void up(long x) { int start=Math.max(a.length-1-18, 1); TreeSet<Integer>ts=new TreeSet<Integer>(); for(int i=start;i<a.length;i++) { ts.add(i); } int r=a.length-1-start; long X=x; while(r>0) { for(int i:ts) { // pw.println(X+" "+fac[r]); if(X/fac[r]==0) { a[a.length-1-r]=i+a[a.length-2-r]; ts.remove(i); // pw.println(r+" "+start+" "+i); // // pw.println(Arrays.toString(a)); break; } X-=fac[r]; } r--; } } public static void main(String[] args) throws Exception { fac=new long[19]; fac[0]=1; for(int i=1;i<19;i++)fac[i]=fac[i-1]*i; int n=sc.nextInt(); int q=sc.nextInt(); a=new long[n+1]; for(int i=1;i<=n;i++) { a[i]=(i)+a[i-1]; } // pw.println(Arrays.toString(a)); long x=0; for(int i=0;i<q;i++) { int t=sc.nextInt(); if(t==2) { x+=sc.nextLong(); } else { up(x); pw.println(-(a[sc.nextInt()-1]-a[sc.nextInt()])); } } pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["4 4\n1 2 4\n2 3\n1 1 2\n1 3 4"]
4 seconds
["9\n4\n6"]
NoteInitially, the permutation has the form $$$[1, 2, 3, 4]$$$. Queries processing is as follows: $$$2 + 3 + 4 = 9$$$; $$$[1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]$$$; $$$1 + 3 = 4$$$; $$$4 + 2 = 6$$$
Java 8
standard input
[ "two pointers", "brute force", "math" ]
d458a65b351b2ba7f9891178ef1b64a1
The first line contains two integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$), where $$$n$$$ — the length of the initial permutation, and $$$q$$$ — the number of queries. The next $$$q$$$ lines contain a single query of the $$$1$$$-st or $$$2$$$-nd type. The $$$1$$$-st type query consists of three integers $$$1$$$, $$$l$$$ and $$$r$$$ $$$(1 \le l \le r \le n)$$$, the $$$2$$$-nd type query consists of two integers $$$2$$$ and $$$x$$$ $$$(1 \le x \le 10^5)$$$. It is guaranteed that all requests of the $$$2$$$-nd type are possible to process.
2,400
For each query of the $$$1$$$-st type, output on a separate line one integer — the required sum.
standard output
PASSED
f7d1188ba84f0948e4ce43e2a8574de4
train_003.jsonl
1604327700
A permutation is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ — are permutations, and $$$[1, 1]$$$, $$$[4, 3, 1]$$$, $$$[2, 3, 4]$$$ — no.Permutation $$$a$$$ is lexicographically smaller than permutation $$$b$$$ (they have the same length $$$n$$$), if in the first index $$$i$$$ in which they differ, $$$a[i] &lt; b[i]$$$. For example, the permutation $$$[1, 3, 2, 4]$$$ is lexicographically smaller than the permutation $$$[1, 3, 4, 2]$$$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation $$$a$$$ of length $$$n$$$ — is the lexicographically smallest permutation $$$b$$$ of length $$$n$$$ that lexicographically larger than $$$a$$$. For example: for permutation $$$[2, 1, 4, 3]$$$ the next permutation is $$$[2, 3, 1, 4]$$$; for permutation $$$[1, 2, 3]$$$ the next permutation is $$$[1, 3, 2]$$$; for permutation $$$[2, 1]$$$ next permutation does not exist. You are given the number $$$n$$$ — the length of the initial permutation. The initial permutation has the form $$$a = [1, 2, \ldots, n]$$$. In other words, $$$a[i] = i$$$ ($$$1 \le i \le n$$$).You need to process $$$q$$$ queries of two types: $$$1$$$ $$$l$$$ $$$r$$$: query for the sum of all elements on the segment $$$[l, r]$$$. More formally, you need to find $$$a[l] + a[l + 1] + \ldots + a[r]$$$. $$$2$$$ $$$x$$$: $$$x$$$ times replace the current permutation with the next permutation. For example, if $$$x=2$$$ and the current permutation has the form $$$[1, 3, 4, 2]$$$, then we should perform such a chain of replacements $$$[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$$$. For each query of the $$$1$$$-st type output the required sum.
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; import java.util.List; public class Coding { private static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); static long[] segmentTree = new long[4*200000 + 11]; public static void main(String[] args) { try { run(); } catch (Exception e) { e.printStackTrace(); } } public static void run() throws Exception { InputModule inp = new InputModule(); OutputModule out = new OutputModule(); long[] fact = new long[15]; fact[0] = 1; for(int i=1;i<=14;++i) fact[i] = fact[i-1]*i; int t = 1; while (t > 0) { int[] ints = inp.cinIntArray(2); int n = ints[0]; int q = ints[1]; long[] cum = new long[n]; for(int i=0;i<n;++i) cum[i] = (i==0?1:(cum[i-1]+i+1)); long sum = 0; int stIndex = n-Math.min(n, 15); while (q>0) { ints = inp.cinIntArray(); if (ints[0] == 1) { int ql = ints[1] -1; int qr = ints[2] - 1; if (qr<stIndex) { out.printLong(cum[qr] - (ql==0?0:cum[ql-1])); } else { long ans = 0; if (ql<stIndex) { ans+=(cum[stIndex-1]-(ql==0?0:cum[ql-1])); } int[] vis = new int[n-stIndex]; for(int i=0;i<n-stIndex;++i) vis[i] = 0; long cur = sum+1; for(int i=stIndex;i<=qr;++i) { int count = 0; while (cur - fact[n - 1 - i] > 0) { cur -= fact[n - 1 - i]; count++; } long val = 0; for(int j=0;j<n-stIndex;++j) { if (vis[j]==0) { if (count == 0) { val = stIndex + 1 + j; vis[j] = 1; break; } else { count--; } } } if (i>=ql) { ans+=val; } } out.printLong(ans); } } else { sum+=ints[1]; } q--; } t--; } } private static class InputModule { private int cinInt() throws Exception { return Integer.parseInt(bi.readLine().split(" ")[0].trim()); } private long cinLong() throws Exception { return Long.parseLong(bi.readLine().split(" ")[0].trim()); } private Double cinDouble() throws Exception { return Double.parseDouble(bi.readLine().split(" ")[0].trim()); } private String cinString() throws Exception { return bi.readLine(); } private int[] cinIntArray(int n) throws Exception { String input = bi.readLine(); String[] values = input.split(" "); int[] ar = new int[n]; for (int i = 0; i < n; ++i) { ar[i] = Integer.parseInt(values[i]); } return ar; } private int[] cinIntArray() throws Exception { String input = bi.readLine(); String[] values = input.split(" "); int[] ar = new int[values.length]; for (int i = 0; i < values.length; ++i) { ar[i] = Integer.parseInt(values[i]); } return ar; } private long[] cinLongArray(int n) throws Exception { String input = bi.readLine(); String[] values = input.split(" "); long[] ar = new long[n]; for (int i = 0; i < n; ++i) { ar[i] = Long.parseLong(values[i]); } return ar; } private String[] cinStringArray(int n) throws Exception { return bi.readLine().split(" "); } } private static class OutputModule { private void printInt(int ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printLong(long ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printDouble(Double ans) throws Exception { writer.append(String.format("%.10f", ans)); writer.append("\n"); writer.flush(); } private void printString(String ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printIntArray(int[] ans) throws Exception { for (int i = 0; i < ans.length; ++i) { writer.append(ans[i] + " "); } writer.append("\n"); writer.flush(); } private void printLongArray(long[] ans) throws Exception { for (int i = 0; i < ans.length; ++i) { writer.append(ans[i] + " "); } writer.append("\n"); writer.flush(); } private void printIntMatrix(int[][] mat, int n, int m) throws Exception { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { writer.append(mat[i][j] + " "); } writer.append("\n"); } writer.flush(); } private void printLongMatrix(long[][] mat, int n, int m) throws Exception { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { writer.append(mat[i][j] + " "); } writer.append("\n"); } writer.flush(); } private void printPoint(Point p) throws Exception { writer.append(p.x + " " + p.y + "\n"); writer.flush(); } private void printPoints(List<Point> p) throws Exception { for (Point pp : p) { writer.append(pp.x + " " + pp.y + "\n"); } writer.flush(); } } }
Java
["4 4\n1 2 4\n2 3\n1 1 2\n1 3 4"]
4 seconds
["9\n4\n6"]
NoteInitially, the permutation has the form $$$[1, 2, 3, 4]$$$. Queries processing is as follows: $$$2 + 3 + 4 = 9$$$; $$$[1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]$$$; $$$1 + 3 = 4$$$; $$$4 + 2 = 6$$$
Java 8
standard input
[ "two pointers", "brute force", "math" ]
d458a65b351b2ba7f9891178ef1b64a1
The first line contains two integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$), where $$$n$$$ — the length of the initial permutation, and $$$q$$$ — the number of queries. The next $$$q$$$ lines contain a single query of the $$$1$$$-st or $$$2$$$-nd type. The $$$1$$$-st type query consists of three integers $$$1$$$, $$$l$$$ and $$$r$$$ $$$(1 \le l \le r \le n)$$$, the $$$2$$$-nd type query consists of two integers $$$2$$$ and $$$x$$$ $$$(1 \le x \le 10^5)$$$. It is guaranteed that all requests of the $$$2$$$-nd type are possible to process.
2,400
For each query of the $$$1$$$-st type, output on a separate line one integer — the required sum.
standard output
PASSED
8af259e180e96ca14d4a44803eda08e9
train_003.jsonl
1604327700
A permutation is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ — are permutations, and $$$[1, 1]$$$, $$$[4, 3, 1]$$$, $$$[2, 3, 4]$$$ — no.Permutation $$$a$$$ is lexicographically smaller than permutation $$$b$$$ (they have the same length $$$n$$$), if in the first index $$$i$$$ in which they differ, $$$a[i] &lt; b[i]$$$. For example, the permutation $$$[1, 3, 2, 4]$$$ is lexicographically smaller than the permutation $$$[1, 3, 4, 2]$$$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation $$$a$$$ of length $$$n$$$ — is the lexicographically smallest permutation $$$b$$$ of length $$$n$$$ that lexicographically larger than $$$a$$$. For example: for permutation $$$[2, 1, 4, 3]$$$ the next permutation is $$$[2, 3, 1, 4]$$$; for permutation $$$[1, 2, 3]$$$ the next permutation is $$$[1, 3, 2]$$$; for permutation $$$[2, 1]$$$ next permutation does not exist. You are given the number $$$n$$$ — the length of the initial permutation. The initial permutation has the form $$$a = [1, 2, \ldots, n]$$$. In other words, $$$a[i] = i$$$ ($$$1 \le i \le n$$$).You need to process $$$q$$$ queries of two types: $$$1$$$ $$$l$$$ $$$r$$$: query for the sum of all elements on the segment $$$[l, r]$$$. More formally, you need to find $$$a[l] + a[l + 1] + \ldots + a[r]$$$. $$$2$$$ $$$x$$$: $$$x$$$ times replace the current permutation with the next permutation. For example, if $$$x=2$$$ and the current permutation has the form $$$[1, 3, 4, 2]$$$, then we should perform such a chain of replacements $$$[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$$$. For each query of the $$$1$$$-st type output the required sum.
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; import java.util.List; public class Coding { private static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); static long[] segmentTree = new long[4*200000 + 11]; public static void main(String[] args) { try { run(); } catch (Exception e) { e.printStackTrace(); } } public static void run() throws Exception { InputModule inp = new InputModule(); OutputModule out = new OutputModule(); long[] fact = new long[15]; fact[0] = 1; for(int i=1;i<=14;++i) fact[i] = fact[i-1]*i; int t = 1; while (t > 0) { int[] ints = inp.cinIntArray(2); int n = ints[0]; int q = ints[1]; int[] ar = new int[n]; for(int i=0;i<n;++i) ar[i] = i+1; buildTree(0, 0, n-1, ar); long sum = 0; HashMap<Integer, Integer> mp = new HashMap<>(); for(int i=0;i<n;++i) { mp.put(ar[i], i); } while (q>0) { ints = inp.cinIntArray(); //System.out.println(ints.length + " " + ints[0]); if (ints[0] == 1) { if (sum>0) { long curr = 0; int start = (n - Math.min(15, n)); int maxm = ar[n-1]; for (int i = n - 2; i >= 0; --i) { int cn = 0; List<Integer> grt = new ArrayList<>(); for (int j = i + 1; j <= n - 1; ++j) if (ar[j] > ar[i]) { cn++; grt.add(ar[j]); } if ((curr + (fact[n - 1 - i] * cn)) >= sum) { //System.out.println("curr is " + curr + " at index " + i); sum -= curr; int ct = 0; while (sum - fact[n - 1 - i] > 0) { ct++; sum -= fact[n-1-i]; } //System.out.println("ct is " + ct); Collections.sort(grt); ar[mp.get(grt.get(ct))] = ar[i]; mp.put(ar[i], mp.get(grt.get(ct))); ar[i] = grt.get(ct); //out.printIntArray(ar); mp.put(grt.get(ct), i); updateTree(0, 0, n-1, i, ar); List<Integer> cur = new ArrayList<>(); for(int j=i+1;j<=n-1;++j) cur.add(ar[j]); Collections.sort(cur); for(int j=i+1;j<=n-1;++j) { ar[j] = cur.get(j-i-1); mp.put(ar[j], j); updateTree(0, 0, n-1, j, ar); } //out.printIntArray(ar); start = i+1; break; } else { curr+=(fact[n - 1 - i] * cn); } maxm = Math.max(maxm, ar[i]); } //System.out.println("Now start is " + start); while (start<=n-1) { int ct = start; while (sum-fact[n-1-start]>0) { sum-=fact[n-1-start]; ct++; } if (ct!=start) { int save = ar[ct]; for(int i = ct;i>=start+1;--i) { ar[i] = ar[i-1]; mp.put(ar[i-1], i); updateTree(0, 0, n-1, i, ar); } ar[start] = save; mp.put(save, start); updateTree(0, 0, n-1, start, ar); } start++; } //out.printIntArray(ar); sum = 0; } out.printLong(query(0, 0, n-1, ints[1]-1, ints[2]-1)); } else { sum+=ints[1]; } q--; } t--; } } private static void buildTree(int idx, int l, int r, int[] ar) { if (l==r) { segmentTree[idx] = ar[l]; } else { int mi = (l+r)/2; buildTree(2*idx+1, l, mi, ar); buildTree(2*idx+2, mi+1, r, ar); segmentTree[idx] = segmentTree[2*idx+1] + segmentTree[2*idx+2]; } } private static void updateTree(int idx, int l, int r, int id, int[] ar) { if (l==r) { segmentTree[idx] = ar[l]; } else { int mi = (l+r)/2; if (id<=mi) { updateTree(2 * idx + 1, l, mi, id, ar); } else { updateTree(2 * idx + 2, mi + 1, r, id, ar); } segmentTree[idx] = segmentTree[2*idx+1] + segmentTree[2*idx+2]; } } private static long query(int idx, int l, int r, int ql, int qr) { if (ql>r||qr<l) { return 0; } else if (ql<=l && qr>=r) { return segmentTree[idx]; } else { int mid = (l+r)/2; return query(2*idx+1, l, mid, ql, qr) + query(2*idx+2, mid+1, r, ql, qr); } } private static class InputModule { private int cinInt() throws Exception { return Integer.parseInt(bi.readLine().split(" ")[0].trim()); } private long cinLong() throws Exception { return Long.parseLong(bi.readLine().split(" ")[0].trim()); } private Double cinDouble() throws Exception { return Double.parseDouble(bi.readLine().split(" ")[0].trim()); } private String cinString() throws Exception { return bi.readLine(); } private int[] cinIntArray(int n) throws Exception { String input = bi.readLine(); String[] values = input.split(" "); int[] ar = new int[n]; for (int i = 0; i < n; ++i) { ar[i] = Integer.parseInt(values[i]); } return ar; } private int[] cinIntArray() throws Exception { String input = bi.readLine(); String[] values = input.split(" "); int[] ar = new int[values.length]; for (int i = 0; i < values.length; ++i) { ar[i] = Integer.parseInt(values[i]); } return ar; } private long[] cinLongArray(int n) throws Exception { String input = bi.readLine(); String[] values = input.split(" "); long[] ar = new long[n]; for (int i = 0; i < n; ++i) { ar[i] = Long.parseLong(values[i]); } return ar; } private String[] cinStringArray(int n) throws Exception { return bi.readLine().split(" "); } } private static class OutputModule { private void printInt(int ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printLong(long ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printDouble(Double ans) throws Exception { writer.append(String.format("%.10f", ans)); writer.append("\n"); writer.flush(); } private void printString(String ans) throws Exception { writer.append(ans + "\n"); writer.flush(); } private void printIntArray(int[] ans) throws Exception { for (int i = 0; i < ans.length; ++i) { writer.append(ans[i] + " "); } writer.append("\n"); writer.flush(); } private void printLongArray(long[] ans) throws Exception { for (int i = 0; i < ans.length; ++i) { writer.append(ans[i] + " "); } writer.append("\n"); writer.flush(); } private void printIntMatrix(int[][] mat, int n, int m) throws Exception { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { writer.append(mat[i][j] + " "); } writer.append("\n"); } writer.flush(); } private void printLongMatrix(long[][] mat, int n, int m) throws Exception { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { writer.append(mat[i][j] + " "); } writer.append("\n"); } writer.flush(); } private void printPoint(Point p) throws Exception { writer.append(p.x + " " + p.y + "\n"); writer.flush(); } private void printPoints(List<Point> p) throws Exception { for (Point pp : p) { writer.append(pp.x + " " + pp.y + "\n"); } writer.flush(); } } }
Java
["4 4\n1 2 4\n2 3\n1 1 2\n1 3 4"]
4 seconds
["9\n4\n6"]
NoteInitially, the permutation has the form $$$[1, 2, 3, 4]$$$. Queries processing is as follows: $$$2 + 3 + 4 = 9$$$; $$$[1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]$$$; $$$1 + 3 = 4$$$; $$$4 + 2 = 6$$$
Java 8
standard input
[ "two pointers", "brute force", "math" ]
d458a65b351b2ba7f9891178ef1b64a1
The first line contains two integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$), where $$$n$$$ — the length of the initial permutation, and $$$q$$$ — the number of queries. The next $$$q$$$ lines contain a single query of the $$$1$$$-st or $$$2$$$-nd type. The $$$1$$$-st type query consists of three integers $$$1$$$, $$$l$$$ and $$$r$$$ $$$(1 \le l \le r \le n)$$$, the $$$2$$$-nd type query consists of two integers $$$2$$$ and $$$x$$$ $$$(1 \le x \le 10^5)$$$. It is guaranteed that all requests of the $$$2$$$-nd type are possible to process.
2,400
For each query of the $$$1$$$-st type, output on a separate line one integer — the required sum.
standard output
PASSED
319a37f0317763d4ff6b8ae691c9ef68
train_003.jsonl
1604327700
A permutation is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ — are permutations, and $$$[1, 1]$$$, $$$[4, 3, 1]$$$, $$$[2, 3, 4]$$$ — no.Permutation $$$a$$$ is lexicographically smaller than permutation $$$b$$$ (they have the same length $$$n$$$), if in the first index $$$i$$$ in which they differ, $$$a[i] &lt; b[i]$$$. For example, the permutation $$$[1, 3, 2, 4]$$$ is lexicographically smaller than the permutation $$$[1, 3, 4, 2]$$$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation $$$a$$$ of length $$$n$$$ — is the lexicographically smallest permutation $$$b$$$ of length $$$n$$$ that lexicographically larger than $$$a$$$. For example: for permutation $$$[2, 1, 4, 3]$$$ the next permutation is $$$[2, 3, 1, 4]$$$; for permutation $$$[1, 2, 3]$$$ the next permutation is $$$[1, 3, 2]$$$; for permutation $$$[2, 1]$$$ next permutation does not exist. You are given the number $$$n$$$ — the length of the initial permutation. The initial permutation has the form $$$a = [1, 2, \ldots, n]$$$. In other words, $$$a[i] = i$$$ ($$$1 \le i \le n$$$).You need to process $$$q$$$ queries of two types: $$$1$$$ $$$l$$$ $$$r$$$: query for the sum of all elements on the segment $$$[l, r]$$$. More formally, you need to find $$$a[l] + a[l + 1] + \ldots + a[r]$$$. $$$2$$$ $$$x$$$: $$$x$$$ times replace the current permutation with the next permutation. For example, if $$$x=2$$$ and the current permutation has the form $$$[1, 3, 4, 2]$$$, then we should perform such a chain of replacements $$$[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$$$. For each query of the $$$1$$$-st type output the required sum.
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(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } void work() { int n=ni(),q=ni(); if(n<=15){ int cur=1; for(;q>0;q--){ int t=ni(); if(t==1){ int l=ni()-1,r=ni()-1; long[] A=new long[n]; boolean[] vis=new boolean[n+1]; long remain=cur; for(int c=n-1;c>=0;c--){ long b=count(c); long v=remain/b+1; if(remain%b==0)v--; for(int i=1,cnt=0;i<=n&&cnt<v;i++){ if(!vis[i]){ cnt++; if(cnt==v){ vis[i]=true; A[n-1-c]=i; } } } remain-=(v-1)*b; } long ret=0; for(int i=l;i<=r;i++){ ret+=A[i]; } out.println(ret); }else{ cur+=ni(); } } }else{ int vv=1; long cur=1; long[] sum=new long[n+1]; for(int i=1;i<=n;i++){ sum[i]=i+sum[i-1]; } int start=n-14; for(;q>0;q--){ int t=ni(); if(t==1){ int l=ni(),r=ni(); long[] A=new long[15]; boolean[] vis=new boolean[16]; long remain=cur; for(int c=14;c>=0;c--){ long b=count(c); long v=remain/b+1; if(remain%b==0)v--; for(int i=1,cnt=0;i<=15&&cnt<v;i++){ if(!vis[i]){ cnt++; if(cnt==v){ vis[i]=true; A[14-c]=i; } } } remain-=(v-1)*b; } if(start>r){ out.println(sum[r]-sum[l-1]); }else if(l<start&&r>=start){ long ret=sum[start-1]-sum[l-1]; for(int i=start;i<=r;i++){ ret+=A[i-start]+n-15; } out.println(ret); }else{ long ret=0; for(int i=l;i<=r;i++){ ret+=A[i-start]+n-15; } out.println(ret); } }else{ cur+=ni(); } } } } long count(int c){ long ret=1; for(int i=1;i<=c;i++){ ret*=i; } return ret; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w,i}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4 4\n1 2 4\n2 3\n1 1 2\n1 3 4"]
4 seconds
["9\n4\n6"]
NoteInitially, the permutation has the form $$$[1, 2, 3, 4]$$$. Queries processing is as follows: $$$2 + 3 + 4 = 9$$$; $$$[1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]$$$; $$$1 + 3 = 4$$$; $$$4 + 2 = 6$$$
Java 8
standard input
[ "two pointers", "brute force", "math" ]
d458a65b351b2ba7f9891178ef1b64a1
The first line contains two integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$), where $$$n$$$ — the length of the initial permutation, and $$$q$$$ — the number of queries. The next $$$q$$$ lines contain a single query of the $$$1$$$-st or $$$2$$$-nd type. The $$$1$$$-st type query consists of three integers $$$1$$$, $$$l$$$ and $$$r$$$ $$$(1 \le l \le r \le n)$$$, the $$$2$$$-nd type query consists of two integers $$$2$$$ and $$$x$$$ $$$(1 \le x \le 10^5)$$$. It is guaranteed that all requests of the $$$2$$$-nd type are possible to process.
2,400
For each query of the $$$1$$$-st type, output on a separate line one integer — the required sum.
standard output
PASSED
733872c24d9837f2ecbf95ab0875ca05
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.*; public class R365B { public static void main(String[] args) throws IOException, NumberFormatException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); Scanner s = new Scanner(System.in); String[] split = f.readLine().split("\\s+"); int n = Integer.parseInt(split[0]), k =Integer.parseInt(split[1]); int[] beauty = new int[n+2]; split = f.readLine().split("\\s+"); long sum = 0, startSum = 0; boolean[] isCapital = new boolean[n+2]; for(int i = 1; i <= n; i++) { beauty[i] = Integer.parseInt(split[i-1]); startSum += beauty[i]; } beauty[n+1] = beauty[1]; beauty[0] = beauty[n]; // System.out.println(Arrays.toString(beauty)); for(int i = 1; i <= n; i++) sum += beauty[i-1] * beauty[i]; // System.out.println(Arrays.toString(beauty)); split = f.readLine().split("\\s+"); ArrayList<Integer> capIndices = new ArrayList<Integer>(); for(int i = 0; i < k; i++) { int index = Integer.parseInt(split[i]); capIndices.add(index); isCapital[index] = true; } // System.out.println(sum); long capitalsDone = 0; for(int i = 0; i < capIndices.size(); i++) { // System.out.println("SUMBefore: " + sum); int index = capIndices.get(i); // System.out.println("I" + index); long add = startSum - beauty[index]; // System.out.printf("%d %d %d\n", beauty[index], beauty[index-1], beauty[index+1]); add -= capitalsDone; if(!isCapital[index-1]) add -= beauty[index-1]; // System.out.println(add); if(index == n && !isCapital[1]) { // System.out.println(1); add -= beauty[index+1]; } else if(index != n) { // System.out.println(2); add -= beauty[index+1]; } // System.out.println(add*beauty[index]); sum += Math.max(0,add)*beauty[index]; capitalsDone += beauty[index]; // System.out.println("SUMAFter: " + sum); // System.out.println(); } System.out.println(sum); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
4e1d59723233ae5539f7d03ed5740722
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * Created by Алексей on 07/20/2016. */ public class IDontKnow { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); final int MAXVALUE = 100_002; List<Integer> ls = new ArrayList<>(MAXVALUE); long sumLocal = 0; ls.add(0); for(int i=1; i<=n; i++){ ls.add(in.nextInt()); sumLocal+=ls.get(i); } ls.set(0, ls.get(n)); ls.add(ls.get(1)); List<Integer> payRoad = new ArrayList<>(MAXVALUE); payRoad.add(0); for(int i=1; i<=n; i++){ payRoad.add(ls.get(i-1)*ls.get(i)); } payRoad.set(0, payRoad.get(n)); payRoad.add(payRoad.get(1)); long answer =0; for(int i=1; i<=n; i++){ answer+=payRoad.get(i); } long sumCapital =0 ; long sumSubtract = 0; boolean []hasVertix = new boolean[MAXVALUE]; for(int i=0; i<m; i++){ int capital = in.nextInt(); if(hasVertix[capital-1] == true){ sumSubtract=ls.get(capital-1); } if(capital==n && hasVertix[1]==true){ sumSubtract+=ls.get(1); } answer+=(sumLocal-ls.get(capital-1)-ls.get(capital+1)-ls.get(capital)- (sumCapital-sumSubtract))*ls.get(capital); sumCapital+=ls.get(capital); hasVertix[capital] = true; sumSubtract=0; } out.println(answer); } } static class InputReader { BufferedReader br; StringTokenizer st; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } // public Character nextChar() {return next().charAt(0);} public void newFile() { try { FileWriter write = new FileWriter(file); write.write(1); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
391f663412e5e9230a51e1e2d8463304
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class _365div2Q2 { public static void main(String[] args) throws IOException { FastScanner obj = new FastScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = obj.nextInt(); int k = obj.nextInt(); int[] arr = obj.nextIntArray(); int[] ka = obj.nextIntArray(); int[] special = new int[n]; for(int i=0;i<k;i++) special[ka[i]-1] = 1; long sum1 = 0; for(int i =0;i<n;i++) sum1 = sum1+arr[i]; long sum2 = 0; long sum = 0; for(int i=0;i<k;i++) { sum += arr[ka[i]-1]*(sum1-arr[ka[i]-1]); sum1 -= arr[ka[i]-1]; } for(int i=0;i<n;i++) if(special[i]==0 && special[(i+1)%n]==0) sum += arr[i]*arr[(i+1)%n]; out.println(sum); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------FastScanner class for faster input---------- public static class FastScanner { BufferedReader br; StringTokenizer tokenizer; public FastScanner() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(br.readLine().trim()); } String next() { while (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray() throws IOException { String[] line = br.readLine().trim().split(" "); int[] out = new int[line.length]; for (int i = 0; i < line.length; i++) { out[i] = Integer.valueOf(line[i]); } return out; } BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
a4426512611e87d23a72d366d5a3624b
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
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 Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); HashMap<Integer,Boolean> h = new HashMap(); int cities = sc.nextInt(); int capitalCities = sc.nextInt(); long val[] = new long[cities]; long allSum = 0; long capSum = 0; for(int i=0;i<cities;i++) { val[i] = sc.nextInt(); h.put(i, false); allSum += val[i]; } int cap[] = new int[capitalCities]; for(int i=0;i<capitalCities;i++) { cap[i] = sc.nextInt(); h.put(cap[i]-1, true); capSum += val[cap[i]-1]; } long sum,ans; sum=0; ans=0; for(int i=0;i<capitalCities;i++) { sum += ((allSum-val[cap[i]-1])*val[cap[i]-1]); } sum += (allSum-capSum)*(capSum); sum /=2; for(int i=0;i<cities;i++) { if(h.get((i)%cities)==false && h.get((i+1)%cities)==false) { sum += val[i%cities]*val[(i+1)%cities]; } } System.out.println(sum); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
6859527102d9bb3971dd1e87354f1aa6
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
/* * Code Author: Jayesh Udhani * Institute : DA-IICT * 3rd year BTech ICT Student */ import java.io.*; import java.util.*; public class CF365B { private static int[] nextIntArray(InputReader in,int n) { int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); return a; } private static void show(int[] a) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } private static void show2DArray(char[][] a) { for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) System.out.print(a[i][j]); System.out.println(); } } static class Pair { private int first; private int second; public Pair(int i, int j) { this.first = i; this.second = j; } public int getFirst() { return first; } public int getSecond() { return second ;} public void setFirst(int k) { this.first=k ; } public void setSecond(int k) { this.second=k ;} } public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); /*------------------------------My Code starts here------------------------------*/ int n,k,i=0,s=0; n=in.nextInt(); k=in.nextInt(); int[] a=nextIntArray(in, n); int[] b=nextIntArray(in, k); for(;i<n;i++) s+=a[i]; HashSet<Integer> h=new HashSet<>(); for(i=0;i<k;i++) h.add(b[i]); long ans=0; boolean x=false; for(i=0;i<n;i++) { if(h.contains(i+1)) { if(x) ans+=(long)a[i]*(long)(s-a[i]); else ans+=(long)a[i]*(long)(s-a[i]-((i-1>=0)?(a[i-1]):(0))); s=s-a[i]; x=true; } else { x=false; if(i+1<n) ans+=(long)a[i]*(long)a[i+1]; else { if(!h.contains(1)) ans+=(long)a[i]*(long)a[0]; } } } out.println(ans); out.close(); /*------------------------------The End------------------------------------------*/ } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
8d3322d33ad5be7f93a5120b83b91eea
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class MishkaAndTrip { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int K = sc.nextInt(); long[] C = new long[N]; long allSum = 0; for (int i = 0; i < N; i++) { C[i] = sc.nextLong(); allSum += C[i]; } boolean[] cap = new boolean[N]; for (int i = 0; i < K; i++) { int ID = sc.nextInt() - 1; cap[ID] = true; } long ans = 0; long capSum = 0; for (int i = 0; i < N; i++) { int prev = (i - 1 + N) % N; if (cap[i]) { ans += C[i] * (allSum - capSum - C[i]); capSum += C[i]; } else if (!cap[prev]) { ans += C[i] * C[prev]; } } System.out.println(ans); } 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 int[] nextIntArray(int n, int offset) { int[] arr = new int[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = 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; } public long[] nextLongArray(int n, int offset) { long[] arr = new long[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
53a35cf36e9845923fae986906173d25
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class MishkaAndTrip { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int K = sc.nextInt(); long[] C = sc.nextLongArray(N); int[] capIDs = new int[K]; boolean[] cap = new boolean[N]; long capSum = 0; for (int i = 0; i < K; i++) { int ID = sc.nextInt() - 1; capIDs[i] = ID; cap[ID] = true; capSum += C[ID]; } long ans = 0; for (int i = 0; i < N; i++) { int prev = (i - 1 + N) % N; ans += C[i] * (capSum + C[prev]); } long tmpSum = 0; for (int i = 0; i < K; i++) { int curr = capIDs[i]; int prev = (curr - 1 + N) % N; int next = (curr + 1) % N; tmpSum += C[curr]; ans -= C[curr] * (tmpSum + C[prev] + C[next]); if (cap[curr] && cap[prev]) { ans += C[curr] * C[prev]; } } System.out.println(ans); } 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 int[] nextIntArray(int n, int offset) { int[] arr = new int[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = 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; } public long[] nextLongArray(int n, int offset) { long[] arr = new long[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
522301c826bfa582f9d808a9c65dda7f
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class MishkaAndTrip { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int K = sc.nextInt(); long[] C = sc.nextLongArray(N); int[] capIDs = new int[K]; boolean[] cap = new boolean[N]; for (int i = 0; i < K; i++) { int ID = sc.nextInt() - 1; capIDs[i] = ID; cap[ID] = true; } long allSum = 0; for (int i = 0; i < N; i++) { allSum += C[i]; } long ans = 0; long capSum = 0; for (int i = 0; i < N; i++) { int prev = (i - 1 + N) % N; if (cap[i]) { ans += C[i] * (allSum - capSum - C[i]); capSum += C[i]; } else if (!cap[prev]) { ans += C[i] * C[prev]; } } System.out.println(ans); } 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 int[] nextIntArray(int n, int offset) { int[] arr = new int[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = 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; } public long[] nextLongArray(int n, int offset) { long[] arr = new long[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
0a1b7ec257398226ffdadf954653d2cf
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.Scanner; public class Main { static void solve(Scanner in, PrintWriter out) { int number_citys = in.nextInt(); int number_capitals = in.nextInt(); int[] costs = new int[100001]; long sum_costs = 0; for (int i = 1; i <= number_citys; i++) { costs[i] = in.nextInt(); sum_costs += costs[i]; } boolean[] capitals = new boolean[100001]; for (int i = 1; i <= number_capitals; i++) { int new_capital = in.nextInt(); capitals[new_capital] = true; } long answer = 0; for (int i = 1; i <= number_citys; i++) { if (capitals[i]) { answer += costs[i] * (sum_costs - costs[i]); sum_costs -= costs[i]; } else { if (i == number_citys) { if (!capitals[1]) { answer += costs[i] * costs[1]; } } else { if (!capitals[i + 1]) { answer += costs[i] * costs[i + 1]; } } } } out.print(answer); } public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.flush(); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
f6a44e66a3347918aa8113e4446ab11c
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.*; public class tmp1 { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(); long sum = 0, result = 0; int[] c = new int[n]; for (int i = 0; i < n; i++) { c[i] = in.nextInt(); sum += c[i]; } int[] cap = new int[k]; HashSet<Integer> capitals = new HashSet<Integer>(); long capitalSum = 0; for (int i = 0; i < k; i++) { cap[i] = in.nextInt() - 1; capitals.add(cap[i]); capitalSum += c[cap[i]]; } long currSum = sum; for(int i = 0; i < k; i++) { currSum -= c[cap[i]]; result += c[cap[i]]*(1L)*(currSum); } for (int i = 0; i < n; i++) { int next = (i+1)%n; if(capitals.contains(i)) continue; if(capitals.contains(next)) continue; result += c[i]*(1L)*(c[next]); } out.println(result); out.close(); } static class Node implements Comparable<Node>{ int next; long dist; public Node (int u, int v) { this.next = u; this.dist = v; } public void print() { out.println(next + " " + dist + " "); } public int compareTo(Node n) { return Integer.compare(-this.next, -n.next); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
0cb8db3c56b1e85452151291ad456d93
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class B2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputStream inputStream=System.in; OutputStream outputStream=System.out; InputReader in=new InputReader(inputStream); PrintWriter out=new PrintWriter(outputStream); TaskA_359 solver=new TaskA_359(); solver.solve(1, in, out); out.close(); } static class TaskA_359{ public void solve(int testNumber,InputReader in,PrintWriter out) { int n=in.nextInt(); int nk=in.nextInt(); int a[]=new int[n]; int k[]=new int[nk]; int b[]=new int[n]; long sum=0; long amt=0; for(int i=0;i<n;i++){ a[i]=in.nextInt(); sum+=a[i]; } for(int i=0;i<nk;i++){ k[i]=in.nextInt()-1; b[k[i]]=1; } for(int i=0;i<nk;i++){ amt+=a[k[i]]*(sum-a[k[i]]); sum-=a[k[i]]; } for(int i=0;i<n-1;i++){ if(b[i]==0&&b[i+1]==0){ amt+=a[i]*a[i+1]; } } if(b[0]==0&&b[n-1]==0) amt+=a[0]*a[n-1]; out.println(amt); } } static class InputReader{ private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader=new BufferedReader(new InputStreamReader(stream)); } public String nextLine(){ try{ return reader.readLine(); }catch (IOException e){return null;} } public String nextString(){ while(stt==null||!stt.hasMoreTokens()) { stt=new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt(){ return Integer.parseInt(nextString()); } public long nextLong(){ return Long.parseLong(nextString()); } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
066cb946d4a0ec2325b972fffc20fb8f
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String args[])throws IOException { //Algorithm1 BufferedReader obj=new BufferedReader(new InputStreamReader(System.in)); String temp1[]=obj.readLine().split(" "); int n=Integer.parseInt(temp1[0]); int k=Integer.parseInt(temp1[1]); int cost[]=new int[n+1]; int capital[]=new int[k]; //HashSet<Integer> map[]=new HashSet[n+1]; HashSet<Integer> capitals=new HashSet<>(); // for(int i=1;i<n+1;i++) // { //map[i]=new HashSet<>(); // } String temp2[]=obj.readLine().split(" "); long sum=0,sum2=0,ans=0; int flag=0; String temp3[]=obj.readLine().split(" "); for(int i=0;i<k;i++) { capital[i]=(Integer.parseInt(temp3[i])); capitals.add(Integer.parseInt(temp3[i])); } for(int i=1;i<n+1;i++) { cost[i]=Integer.parseInt(temp2[i-1]); sum2+=(long)cost[i]; } for(int i=1;i<n+1;i++) { if(capitals.contains(i)) { if(flag==1) ans+=(long)cost[i]*(long)(sum2-cost[i]); else { ans+=(long)cost[i]*(long)(sum2-cost[i]-cost[i-1]); } flag=1; sum2-=cost[i]; } else { if(i==n&&!capitals.contains(1)) ans+=cost[i]*cost[1]; else if(i<n) ans+=cost[i]*cost[i+1]; flag=0; } } System.out.println(ans); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
ebff3346d1b3dca0c1c084f3231f7997
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; /** * Created by for on 2017-02-05. */ public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int arr[] = new int[n+1]; long capSum = 0; for (int i = 1; i <= n; i++) { arr[i] = in.nextInt(); capSum += arr[i]; } long sum = arr[1]*arr[n]; for (int i = 1; i < n; i++) { sum = sum + arr[i]*arr[i+1]; } HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < k; i++) { int index = in.nextInt(); int left = 0; int right = 0; if(index == 1) { left = n; } else { left = index -1; } if(index == n) { right = 1; } else { right = index+1; } capSum -= arr[index]; set.add(index); int minus = 0; if(!set.contains(left)) { minus += arr[left]; } if(!set.contains(right)) { minus += arr[right]; } sum += arr[index] * (capSum-minus); } out.println(sum); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
5ad7b263ff9c6b528ad2d595c8456a0e
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class MishaAndTrip { public static void main(String[] args) { Scanner sc = new Scanner(); int n=sc.nextInt(); int k=sc.nextInt(); int[] beauty=new int[n]; boolean[] iscapital=new boolean[n]; long sumofallbeauty=0; for(int i=0;i<n;i++) { beauty[i]=sc.nextInt(); sumofallbeauty+=beauty[i]; } for(int i=0;i<k;i++) { iscapital[sc.nextInt()-1]=true; } long answer=0; for(int i=0;i<n;i++) { if(iscapital[i]) { answer+=beauty[i]*(sumofallbeauty-beauty[i]); sumofallbeauty-=beauty[i]; } } for(int i=0;i<n-1;i++) { if(!iscapital[i]&&!iscapital[i+1]) answer+=beauty[i]*beauty[i+1]; } if(!iscapital[0]&&!iscapital[n-1]) answer+=beauty[0]*beauty[n-1]; System.out.println(answer); } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } static class Scanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
5b2bfd4292828d023a3a58479b2242b8
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[] args) { try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))) { final int n = in.nextInt(), k = in.nextInt(); final int[] a = new int[n], b = new int[k]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < k; i++) { b[i] = in.nextInt() - 1; } System.out.println(solve(a, b)); } } private static long solve(int[] a, int[] b) { long t = Arrays.stream(a).asLongStream().sum(); long ans = 0; final Set<Integer> c = new HashSet<>(); for (int i : b) { ans += (t -= a[i]) * a[i]; c.add(i); } for (int i = 0; i < a.length; i++) { final int j = i == 0 ? a.length : i; if (!c.contains(i) && !c.contains(j - 1)) { ans += a[i] * a[j - 1]; } } return ans; } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
bfb56a5fbfddf6136b890f33c1dee6e9
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class B { public static void main(String[] args) { try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))) { final int n = in.nextInt(), k = in.nextInt(); final int[] a = new int[n], b = new int[k]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < k; i++) { b[i] = in.nextInt() - 1; } System.out.println(solve(a, b)); } } private static long solve(int[] a, int[] b) { long t = Arrays.stream(a).asLongStream().sum(); long ans = 0; int j = 1; for (int i : b) { ans += (t -= a[i]) * a[i]; for (; j < i; j++) { ans += a[j] * a[j - 1]; } j = i + 2; } for (; j < a.length; j++) { ans += a[j] * a[j - 1]; } if (b[0] > 0 && b[b.length - 1] < a.length - 1) { ans += a[0] * a[a.length - 1]; } return ans; } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
9496980995f24ace22521f4d5cf8387e
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[] args) { try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))) { final int n = in.nextInt(), k = in.nextInt(); final int[] a = new int[n], b = new int[k]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < k; i++) { b[i] = in.nextInt() - 1; } System.out.println(solve(a, b)); } } private static long solve(int[] a, int[] b) { long t = Arrays.stream(a).asLongStream().sum(); long ans = 0; final Set<Integer> c = new HashSet<>(); for (int i : b) { ans += (t -= a[i]) * a[i]; c.add(i); } for (int i = 0; i < a.length; i++) { final int j = (i == 0 ? a.length : i) - 1; if (!c.contains(i) && !c.contains(j)) { ans += a[i] * a[j]; } } return ans; } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
041f9f002770cb42ca31f018cb6e48dc
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.InputStream; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; public class OutputBasedSolver { public static void main(String[] args) { new OutputBasedSolver(false, System.in).solve(); } public OutputBasedSolver(boolean hasMultipleTests, InputStream input) { scanner = new Scanner(input); numberOfTests = hasMultipleTests ? scanner.nextInt() : 1; } public ArrayList<String> solve() { preCompute(); for (int i = 0; i < numberOfTests; ++i) { resetData(); if (readInput()) { computeResult(); addCurrentToResults(); printResult(); } else { break; } } return results; } private void addCurrentToResults() { results.add(String.valueOf(result)); } private int numberOfTests; private Scanner scanner; private ArrayList<String> results = new ArrayList<>(); private final int MOD = 1000000007; private long result; private long n; private long k; private ArrayList<Long> beauties; private ArrayList<Long> capitals; private long sumAll; private long sumCapitals; private ArrayList<Long> accumulativeCapitals; private boolean[] capitalChecks; private void preCompute() { } private void resetData() { result = 0; sumAll = 0; sumCapitals = 0; beauties = new ArrayList<>(); capitals = new ArrayList<>(); accumulativeCapitals = new ArrayList<>(); } private boolean readInput() { try { n = scanner.nextLong(); k = scanner.nextLong(); capitalChecks = new boolean[(int) n]; for (int i = 0; i < n; ++i) { beauties.add(scanner.nextLong()); sumAll += beauties.get(i); } for (int i = 0; i < k; ++i) { long cap = scanner.nextLong() - 1; capitals.add(cap); sumCapitals += beauties.get(Math.toIntExact(capitals.get(i))); accumulativeCapitals.add(sumCapitals); capitalChecks[(int) cap] = true; } } catch (NoSuchElementException e) { System.err.println("Not enough input data. "); return false; } return true; } private void printResult() { System.out.println(result); } private void computeResult() { addCapitalPricesWithoutNeighboursAndCapitals(); addRingPrices(); addCapitalRingPrices(); } private void addCapitalPricesWithoutNeighboursAndCapitals() { for (Long capital : capitals) { Long beauty = beauties.get(Math.toIntExact(capital)); result += beauty * (sumAll - beauty); removeNeighbours(capital, beauty); removeOtherCapitals(capital, beauty); } } private void addCapitalRingPrices() { for (int i = 0; i < k; ++i) { long neighbour1 = getLeftNeighbour(capitals.get(i)); long neighbour2 = getRightNeighbour(capitals.get(i)); long sth = 0; if (neighbour1 > capitals.get(i) && isCapital(neighbour1)) { sth += beauties.get((int) neighbour1); } if (isCapital(neighbour2)) { sth += beauties.get((int) neighbour2); } result += beauties.get(Math.toIntExact(capitals.get(i))) * Math.max(0, (accumulativeCapitals.get((int) k - 1) - accumulativeCapitals.get(i) - sth)); } } private void removeOtherCapitals(Long current, Long beauty) { long sth = 0; long neighbour1 = getLeftNeighbour(current); long neighbour2 = getRightNeighbour(current); if (isCapital(neighbour1)) { sth += beauties.get((int) neighbour1); } if (isCapital(neighbour2)) { sth += beauties.get((int) neighbour2); } result -= beauty * (sumCapitals - beauty - sth); } private boolean isCapital(long current) { return capitalChecks[(int) current]; } private void addRingPrices() { for (int i = 0; i < n - 1; ++i) { result += beauties.get(i) * beauties.get(i + 1); } result += beauties.get((int) (n - 1)) * beauties.get(0); } private void removeNeighbours(Long capital, Long beauty) { result -= beauty * beauties.get(Math.toIntExact(getLeftNeighbour(capital))); result -= beauty * beauties.get(Math.toIntExact(getRightNeighbour(capital))); } private Long getLeftNeighbour(Long current) { if (current == 0) { return n - 1; } else { return current - 1; } } private Long getRightNeighbour(Long current) { if (current == n - 1) { return 0L; } else { return current + 1; } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
d0cac5bcff36f8f5c6297749792051b0
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
//package com.company; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { //new Solve(new Scanner(System.in)).runA(); new Solve(new Scanner(System.in)).runB(); } private static class Solve { Scanner sc ; public Solve(Scanner scanner) { sc = scanner; } public void runA() { int n = sc.nextInt(); int chris , misha; chris = misha = 0 ; for(int i = 0 ; i < n ; ++i){ int c = sc.nextInt(); int d = sc.nextInt(); if(c > d){ misha++; }else if(c < d){ chris++; } } String ans = ""; if(chris == misha){ ans = "Friendship is magic!^^"; }else if(chris < misha){ ans = "Mishka"; }else{ ans = "Chris"; } System.out.print(ans); } public void runB() { long n , k ; n = sc.nextLong(); k = sc.nextLong(); long fir , old , cur; fir = sc.nextLong(); long ans = 0 ; ArrayList<Long> ar = new ArrayList<>(); ar.clear(); ar.add(fir); long now = fir; for(long i = 1 ; i < n ; ++i){ cur = sc.nextLong(); ar.add(cur); now += cur; } ArrayList<Long> cap = new ArrayList<>(); boolean []flag = new boolean[(int)n + 10]; for(long j = 0 ; j < k ; ++j){ cur = sc.nextLong(); cap.add(cur); flag[(int)cur] = true; } for(int i = 1 ; i <= n ; ++i){ long tr = ar.get(i -1); if(flag[(int)i]){ now -= tr; ans += tr * now; }else{ if(i == 1){ if(flag[(int)n] == false){ ans += tr * ar.get((int)n -1); } }else{ if(flag[i - 1] == false){ ans+= tr * ar.get((int)i - 2); } } } } System.out.print(ans); } } /* private static class Solve { private static final int SIZE = 900000 + 99; private final Scanner SCANNER ; Set<Integer> public Solve(Scanner scanner) { this.SCANNER = scanner; } public void run(){ int n; hashMap.clear(); while (true){ n = SCANNER.nextInt(); System.out.println(rec(0 , n)); } } private int rec(int i, int n) { if(n == 0){ return 1; }else if(i >= 5 || n < 0){ return 0; }else if(hashMap.containsKey(new MyPair(i , n))){ return hashMap.get(new MyPair(i , n)); }else{ hashMap.put(new MyPair(i , n) , rec(i+1 , n) + rec(i , n - dx[i])); return hashMap.get(new MyPair(i , n)); } } private class MyPair { public int ind; public int rem; public MyPair(int i , int j){ ind = i ; rem= j; } } } */ }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
6e6b9709336eb8664a78797c6b5c8833
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.util.*; import java.io.*; public class Cheker{ public static InputReader sc; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args){ sc=new InputReader(System.in); out=new PrintWriter(System.out); int n=sc.nextInt(); int k=sc.nextInt(); long[] A=new long[n]; long sum=0; for(int i=0;i<n;i++){ A[i]=sc.nextInt(); sum+=A[i]; } Deque<Integer> capital=new LinkedList<Integer>(); for(int i=0;i<k;i++){ int a=sc.nextInt(); capital.addLast(a-1); } long res=0; if(capital.size()==1){ int onlyCap=capital.poll(); res+=A[onlyCap]*(sum-A[onlyCap]); for(int i=1;i<onlyCap;i++){ res+=(A[i]*A[i-1]); } for(int i=onlyCap+2;i<n;i++){ res+=(A[i]*A[i-1]); } if(onlyCap!=0 && onlyCap!=n-1){ res+=(A[0]*A[n-1]); } } else{ int firstCapital=capital.pollFirst(); res+=A[firstCapital]*(sum-A[firstCapital]); sum-=A[firstCapital]; int val=firstCapital; for(int i=1;i<firstCapital;i++){ res+=(A[i]*A[i-1]); } for(Integer a:capital){ res+=A[a]*(sum-A[a]); sum-=A[a]; for(int i=firstCapital+2;i<a;i++){ res+=(A[i]*A[i-1]); } firstCapital=a; } for(int i=capital.peekLast()+2;i<n;i++){ res+=(A[i]*A[i-1]); } if(val!=0 && capital.peekLast()!=n-1){ res+=(A[0]*A[n-1]); } } out.println(res); out.close(); } static int binarySearch(int[] A,int val,int l,int r){ while(l<=r){ int middle=(l+r)>>1; if(val>=A[middle]){ l=middle+1; } else{ r=middle-1; } } return l; } static void shuffle(int[] A){ for(int i=A.length-1;i>0;i--){ int j=(int)(Math.random()*(i+1)); int temp=A[j]; A[j]=A[i]; A[i]=temp; } } public static class Node implements Comparable<Node>{ int next; long dist; public Node (int u, int v) { this.next = u; this.dist = v; } public void print() { out.println(next + " " + dist + " "); } public int compareTo(Node n) { return Integer.compare(-this.next, -n.next); } } public static long pow(int base, long exp) { if(exp == 0) return 1; if(exp == 1) return base; long val = pow(base, exp/2); long result = (val*val)%MOD; if((exp&1) == 1) result = (result*base)%MOD; return result; } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
6667f6d491493162d3c3ea0185d793e9
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.util.*; public class B { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } static long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } static double nextDouble() throws IOException { in.nextToken(); return in.nval; } static String next() throws IOException { in.nextToken(); return in.sval; } static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static int n, k; static int[] c = new int[100005]; static int[] id = new int[100005]; static long ans = 0; static long sum = 0; static long sum2 = 0; public static void main(String[] args) throws IOException { n = nextInt(); k = nextInt(); Arrays.fill(c, 0); for (int i = 1; i <= n; i++) { c[i] = nextInt(); sum += c[i]; } for (int i = 1; i <= k; i++) { int t = nextInt(); id[t] = 1; sum2 += c[t]; } for (int i = 1; i <= n; i++) { if (id[i] == 1) ans += c[i] * (sum - c[i]); } long res1 = 0; for (int i = 1; i <= n; i++) { if (id[i] == 1) { res1 += c[i] * (sum2 - c[i]); } } ans -= res1/2; c[n + 1] = c[1]; id[n + 1] = id[1]; for (int i = 1; i <= n; i++) { if (id[i] == 1 || id[i + 1] == 1) { continue; } ans += c[i] * c[i + 1]; } out.println(ans); out.flush(); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
370dfdb5da3d7c31dce054cee0c33fc0
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; public class codeforces { public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int k=sc.nextInt(); int point[]=new int [n+12]; boolean capital[]=new boolean[100000+10]; long sum=0L; for(int i=0;i<n;i++){ point[i]=sc.nextInt(); sum+=point[i]; } for(int i=0;i<k;i++) { int x =sc.nextInt(); capital[--x]=true; } long ans =0; for(int i=0;i<n;i++){ if(capital[i]){ ans+=point[i]*(sum-point[i]); sum-=point[i]; }else{ if(!capital[(i+1)%n]) ans+=point[i]*point[(i+1)%n]; } } System.out.println(ans); } } /*static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } */ class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
5e2814820a4ef1a7be3ca5b203767634
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static long sum(int [] cities, int [] capitals) { int N = cities.length; boolean [] isCapital = new boolean[N]; long res = 0; long totalBeauty = 0; for(int city : cities) totalBeauty += city; for(int capInd : capitals) { capInd -=1; isCapital[capInd] = true; res += (totalBeauty-cities[capInd])*cities[capInd]; totalBeauty -= cities[capInd]; } for(int i=1; i<N; i++) { if(isCapital[i] || isCapital[i-1]) continue; res += cities[i] * cities[i-1]; } if(!isCapital[0] && !isCapital[N-1]) { res += cities[0] * cities[N-1]; } return res; } public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(br.readLine()); int numCities = Integer.parseInt(tokenizer.nextToken()); int numCapitals = Integer.parseInt(tokenizer.nextToken()); int [] cities = new int[numCities]; int [] capitals = new int[numCapitals]; tokenizer = new StringTokenizer(br.readLine()); for(int i=0; i<numCities; i++) { cities[i] = Integer.parseInt(tokenizer.nextToken()); } tokenizer = new StringTokenizer(br.readLine()); for(int i=0; i<numCapitals; i++) { capitals[i] = Integer.parseInt(tokenizer.nextToken()); } long sol = sum(cities, capitals); System.out.println(sol); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
ba3e37b92139831d15134941224393e8
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static long sum(int [] cities, int [] capitals) { int N = cities.length; boolean [] isCapital = new boolean[N]; long totalBeautyCaps = 0; for(int i=0; i<capitals.length; ++i) { int capInd = capitals[i]-1; isCapital[capInd] = true; totalBeautyCaps += cities[capInd]; } long totalSum = 0; for(int i=1; i<N; i++) { totalSum += (long)cities[i]*(long)cities[i-1]; } totalSum += (long)cities[0] * (long)cities[N-1]; long fromABeauty = 0; long duplicates = 0; for(int i=0; i<N; i++) { long mult = totalBeautyCaps; if(isCapital[i]) { mult -= cities[i]; } if(i>0) { if(isCapital[i-1]) mult -= cities[i-1]; } else { if(isCapital[N-1]) mult -= cities[N-1]; } if(isCapital[(i+1) % N]) mult -= cities[(i+1)%N]; if(isCapital[i]) { duplicates += cities[i]*mult; } else { fromABeauty += cities[i]*mult; } } totalSum += fromABeauty + duplicates/2; return totalSum; } public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(br.readLine()); int numCities = Integer.parseInt(tokenizer.nextToken()); int numCapitals = Integer.parseInt(tokenizer.nextToken()); int [] cities = new int[numCities]; int [] capitals = new int[numCapitals]; tokenizer = new StringTokenizer(br.readLine()); for(int i=0; i<numCities; i++) { cities[i] = Integer.parseInt(tokenizer.nextToken()); } tokenizer = new StringTokenizer(br.readLine()); for(int i=0; i<numCapitals; i++) { capitals[i] = Integer.parseInt(tokenizer.nextToken()); } long sol = sum(cities, capitals); System.out.println(sol); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
6368c687ddf3531fed8f3640f93d1c96
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class CodeForces { private final BufferedReader reader; private final PrintWriter writer; private StringTokenizer tokenizer; private void solve() { int n = nextInt(); int k = nextInt(); long c[] = new long[n]; int capitals[] = new int[k]; long res = 0; long sum = 0; long capitalsSum = 0; for (int i = 0; i < n; i++) c[i] = nextInt(); for (int i = 0; i < k; i++) { capitals[i] = nextInt() - 1; capitalsSum += c[capitals[i]]; } for (int i = 0; i < n; i++) { if (Arrays.binarySearch(capitals, i) < 0) sum += c[i]; if (i > 0) { if (Arrays.binarySearch(capitals, i - 1) < 0 || Arrays.binarySearch(capitals, i) < 0) { res += (c[i] * c[i - 1]); } } } if (Arrays.binarySearch(capitals, 0) < 0 || Arrays.binarySearch(capitals, n - 1) < 0) res += (c[0] * c[n - 1]); for (int i = 0; i < k; i++) { res += (c[capitals[i]] * sum); if (capitals[i] > 0 && capitals[i] < n - 1) { if (Arrays.binarySearch(capitals, capitals[i] - 1) < 0) res -= (c[capitals[i]] * c[capitals[i] - 1]); if (Arrays.binarySearch(capitals, capitals[i] + 1) < 0) res -= (c[capitals[i]] * c[capitals[i] + 1]); } else if (capitals[i] == 0) { if (Arrays.binarySearch(capitals, n - 1) < 0) res -= (c[0] * c[n - 1]); if (Arrays.binarySearch(capitals, 1) < 0) res -= (c[0] * c[1]); } else { if (Arrays.binarySearch(capitals, n - 2) < 0) res -= (c[n - 1] * c[n - 2]); if (Arrays.binarySearch(capitals, 0) < 0) res -= (c[n - 1] * c[0]); } } for (int i = 0; i < k; i++) { capitalsSum -= c[capitals[i]]; res += (c[capitals[i]] * capitalsSum); } writer.print(res); } public static void main(String[] args) { new CodeForces(System.in, System.out); } private CodeForces(InputStream inputStream, OutputStream outputStream) { this.reader = new BufferedReader(new InputStreamReader(inputStream)); this.writer = new PrintWriter(outputStream); solve(); writer.close(); } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } private String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public BigInteger nextBigInteger() { return new BigInteger(next()); } private int upperBinary(long[] array, long key) { int low = 0; int high = array.length - 1; if (high < 0) return -1; while (low < high) { int mid = (low + high + 1) >>> 1; if (array[mid] <= key) low = mid; else high = mid - 1; } if (array[low] != key) { if (array[low] < key) low++; low = -(low + 1); } return low; } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
efce02316f31a4ba6bd17d14b5ebce9d
train_003.jsonl
1470323700
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i &lt; n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a &lt; b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), k = sc.nextInt(); int c[] = new int[n]; for (int i = 0; i < n; i++) { c[i] = sc.nextInt(); } Set<Integer> capitals = new HashSet<>(k); for (int i = 0; i < k; i++) { capitals.add(sc.nextInt()); } long sum = 0; for (int i = 0; i < n; i++) { sum += c[i]; } long result = 0; for (Integer capital : capitals) { sum -= c[capital - 1]; result += c[capital - 1] * sum; } for (int i = 0; i < n - 1; i++) { if(!isCapitals(i, i + 1, capitals)) { result += c[i] * c[i + 1]; } } if(!isCapitals(0, n - 1, capitals)) { result += c[0] * c[n - 1]; } System.out.println(result); } private static boolean isCapitals(int a, int b, Set<Integer> capitals) { return capitals.contains(a + 1) || capitals.contains(b + 1); } }
Java
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
1 second
["17", "71"]
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
Java 8
standard input
[ "implementation", "math" ]
bc6b8fda79c257e6c4e280d7929ed8a1
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
1,400
Print the only integer — summary price of passing each of the roads in XXX.
standard output
PASSED
9796f18c1eb49ba315376e3e06e8a30e
train_003.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int k=input.nextInt(); if(n==1) { System.out.println(-1); System.exit(0); } int arr[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { arr[i][j]=-1; } } boolean is_pos=true; for(int i=1;i<=k;i++) { for(int j=0;j<n;j++) { if(arr[j][(j+i)%n]==0 || arr[j][(j+i)%n]==1) { is_pos=false; break; } arr[j][(j+i)%n]=1; arr[(j+i)%n][j]=0; } if(!is_pos) { break; } } if(!is_pos) { System.out.println(-1); System.exit(0); } int count=0; StringBuilder ans=new StringBuilder(""); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(arr[i][j]==1) { count++; ans.append((i+1)+" "+(j+1)+"\n"); } } } System.out.println(count+"\n"+ans); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
72da349ce1f43d13f8e4ce7367f40a7c
train_003.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
// INKO MERE CODE SE KYA DIKAAT HAIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII import java.io.*; import java.util.*; public class GPL implements Runnable { public static void main(String[] args) { new Thread(new GPL()).run(); } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (n < 2 * k + 1) { out.println(-1); return; } out.println(k * n); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { int next = (i + j + 1) % n; out.println((i + 1) + " " + (next + 1)); } } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
5fd6fa2862776e7b42098cb497bb9c60
train_003.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static boolean[] vis; //line 74 and 91 hasElement ans pth_fnd static int MOD=1000000007; // static int[] ans; static int cnt; static long set1=0,set2=0; // public static void main(String[] args) throws IOException{ // long sttm=System.currentTimeMillis(); FastReader sc=new FastReader(); OutputStream out=new BufferedOutputStream(System.out); int n=sc.nextInt(),k=sc.nextInt(); int[] win=new int[n],lose=new int[n]; ArrayList<Integer[]> arrl=new ArrayList<Integer[]>(); for(int i=0;i<n;i++){ int j=1; while(j<n && win[i]<k){ if(win[(i+j)%n]+lose[(i+j)%n]<n-1){ win[i]++;lose[(i+j)%n]++; arrl.add(new Integer[]{i+1,(i+j)%n+1}); } j++; } } boolean con=true; for(int i=0;i<n;i++){ if(win[i]!=k){ con=false; break; } } if(con){System.out.println(arrl.size());for(int i=0;i<arrl.size();i++){ out.write((arrl.get(i)[0]+" "+arrl.get(i)[1]+"\n").getBytes()); }} else out.write(("-1\n").getBytes()); out.flush(); } public static boolean dfsCycle(ArrayList<Integer>[] arrl,int[] vis,int st,int pr){ vis[st]=1; int cupr=st; for(int elm:arrl[st]){ if(vis[elm]==1 && elm!=pr){ return true; } else if(vis[elm]==0 && dfsCycle(arrl, vis, elm, cupr)){ return true; } } vis[st]=2; return false; } public static long pow(long n,long k){ //n-pow(k) if(k==1){ return n%MOD; } if(k==0){ return 1; } long val=pow(n,k/2)%MOD; if(k%2==0)return ((val%MOD)*(val%MOD))%MOD; else return (((val*val)%MOD)*n)%MOD; } public static HashMap<Integer,Integer> lcm(int num){ ArrayList<Integer> arrl=new ArrayList<Integer>(); HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); while(num%2==0){ if(!map.containsKey(2)){ arrl.add(2); map.put(2, 1); } else{ map.put(2,map.get(2)+1); } num/=2; } for(int i=3;i*i<=num;i+=2){ while(num%i==0){ if(!map.containsKey(i)){ arrl.add(i); map.put(i, 1); } else{ map.put(i,map.get(i)+1); } num/=i; } } if(num>2){ if(!map.containsKey(num)){ arrl.add(num); map.put(num, 1); } else{ map.put(num,map.get(num)+1); } } return map; } static long m=998244353l; static long modInverse(long a,long m) { long m0 = m; long y = 0l, x = 1l; if (m == 1) return 0l; while (a > 1) { long q = a / m; long t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } public static int num_fact(int num){ ArrayList<Integer> arr=new ArrayList<Integer>(); int cnt=0; for(int i=1;i*i<=num;i++){ if(num%i==0){ if(i*i==num){ cnt+=1; } else{ cnt+=2; } } } return cnt; } public static void sort_inc(int[][] arr,int col){ //change dimention if req Arrays.sort(arr, new Comparator<int[]>() { public int compare(final int[] entry1,final int[] entry2) { if (entry1[col] > entry2[col]) //this is for inc return 1; else if(entry1[col]==entry2[col]) return 0; else return -1; } }); } public static boolean prime(int n){ for(int i=2;i*i<=n;i++){ if(n%i==0){ return false; } } return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static long lcmOfTwo(int a,int b){ return a*b/gcd(a,b); } } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
d51c1674223f2f2198202a7698e6b51d
train_003.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.OutputStreamWriter; import java.util.Scanner; import java.io.PrintWriter; public class test { public static void main(String[] args) { Scanner input = new Scanner(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = input.nextInt(); int k = input.nextInt(); if ((n*(n-1))/2 < n*k) { System.out.println(-1); return; } System.out.println(n*k); for (int i = 1; i <= n; i++) { int j = i+1; int t = k; while (t > 0) { if (j % (n+1) == 0) { j++; continue; } out.printf("%d %d\n", i, j%(n+1)); // System.out.printf("%d %d\n", i, j%(n+1)); t--; j++; } } out.flush(); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
61cfe2360e4656c9db43676c71cad94e
train_003.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.util.*; public class GPL implements Runnable { public static void main(String[] args) { new Thread(new GPL()).run(); } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (n < 2 * k + 1) { out.println(-1); return; } out.println(k * n); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { int next = (i + j + 1) % n; out.println((i + 1) + " " + (next + 1)); } } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
2ae6177e8a81d3ad4dcbeb75aa5d02ea
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.util.*; import java.io.*; public class _0208_E_BloodCousins { static ArrayList<Integer> graph[]; static int st[], et[], arr[], time = 0, dep[], par[], sqrtN; public static class Query implements Comparable<Query>{ int l, r, val, id; public Query(int l, int r, int val, int id) { this.l = l; this.r = r; this.val = val; this.id = id; } public int compareTo(Query q) { if(this.l/sqrtN == q.l/sqrtN) return Integer.compare(this.r, q.r); return Integer.compare(this.l/sqrtN, q.l/sqrtN); } } public static void main(String[] args) throws IOException { int N = readInt(); sqrtN = (int) Math.sqrt(N); graph = new ArrayList[N+1]; for(int i = 0; i<=N; i++) graph[i] = new ArrayList<>(); for(int i= 1; i<=N; i++) {int p = readInt(); graph[i].add(p); graph[p].add(i);} st = new int[N+1]; et = new int[N+1]; arr = new int[2*N+1]; dep = new int[N+1]; par = new int[N+1]; dfs(0); int logN = Integer.numberOfTrailingZeros(Integer.highestOneBit(N)); int LCA[][] = new int[logN+2][N+1]; for(int i = 1; i<=N; i++) LCA[0][i] = par[i]; for(int i = 1; i<=logN+1; i++) for(int j = 1; j<=N; j++) LCA[i][j] = LCA[i-1][LCA[i-1][j]]; int Q = readInt(); int ans[] = new int[Q]; Query qu[] = new Query[Q]; for(int q = 0; q<Q; q++) { int n = readInt(), d = readInt(); if(d >= dep[n]) {ans[q] = 1; qu[q] = new Query(-1, -1, -1, -1);} else { for(int i = logN+1; i>=0; i--) if(((1<<i)&d) != 0) n = LCA[i][n]; qu[q] = new Query(st[n], et[n], dep[n]+d, q); } } Arrays.sort(qu); int l = 1, r = 0, tot[] = new int[N+1]; for(int q = 0; q<Q; q++) { int lidx = qu[q].l, ridx = qu[q].r; if(lidx == -1) continue; while(l < lidx) tot[arr[l++]]--; while(l > lidx) tot[arr[--l]]++; while(r < ridx) tot[arr[++r]]++; while(r > ridx) tot[arr[r--]]--; ans[qu[q].id] += tot[Math.abs(qu[q].val)]/2; } for(int n : ans) print((n-1) + " "); exit(); } public static void dfs(int n) { for(int e : graph[n]) if(par[n] != e){ par[e] = n; dep[e] = dep[n] + 1; st[e] = ++time; arr[time] = dep[e]; dfs(e); et[e] = ++time; arr[time] = dep[e]; } } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
29f9a169483fbe786415cc90426233ec
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AlexFetisov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE_BloodyBros solver = new TaskE_BloodyBros(); solver.solve(1, in, out); out.close(); } } class TaskE_BloodyBros { Graph g; public void solve(int testNumber, InputReader in, PrintWriter out) { g = new Graph(); int n = in.nextInt(); g.initGraph(n+1, n); for (int i = 1; i <= n; ++i) { int x = in.nextInt(); g.addEdge(x, i); } int[][] parents = Parent.getLevelParents(g, 0); int countQ = in.nextInt(); final DFSOrder dfsOrder = new DFSOrder(g, 0, parents[0]); int[] vertexLevels = Parent.getVertexLevels(g, 0, parents[0]); int maxLevel = ArrayUtils.getMax(vertexLevels); List<Integer>[] verticesOnLevels = new List[maxLevel+1]; for (int i = 0; i <= maxLevel; ++i) { verticesOnLevels[i] = new ArrayList<Integer>(); } for (int i = 0; i < vertexLevels.length; ++i) { verticesOnLevels[vertexLevels[i]].add(i); } for (int i = 0; i <= maxLevel; ++i) { Collections.sort(verticesOnLevels[i], new Comparator<Integer>() { public int compare(Integer v, Integer u) { return dfsOrder.start(v) - dfsOrder.start(u); } }); } while (countQ-- > 0) { int v = in.nextInt(); int p = in.nextInt(); int x = Parent.getParent(v, p, parents); if (x == -1 || x == 0) { out.print(0 + " "); continue; } else { int startForParent = dfsOrder.start(x); int endForParent = dfsOrder.end(x); int left = 0, right = verticesOnLevels[vertexLevels[v]].size()-1; int begin = -1, end = -1; while (left <= right) { int middle = (left + right) / 2; int cv = verticesOnLevels[vertexLevels[v]].get(middle); if (dfsOrder.start(cv) >= startForParent && dfsOrder.end(cv) <= endForParent) { begin = middle; end = middle; right = middle - 1; } else { if (dfsOrder.start(cv) > endForParent) { right = middle - 1; } else { left = middle + 1; } } } if (begin == -1) throw new AssertionError("!"); left = 0; right = verticesOnLevels[vertexLevels[v]].size()-1; while (left <= right) { int middle = (left + right) / 2; int cv = verticesOnLevels[vertexLevels[v]].get(middle); if (dfsOrder.start(cv) >= startForParent && dfsOrder.end(cv) <= endForParent) { end = middle; left = middle + 1; } else { if (dfsOrder.start(cv) > endForParent) { right = middle - 1; } else { left = middle + 1; } } } out.print(end - begin); out.print(" "); } } } } class Graph { public int[] from; public int[] to; public int[] first; public int[] next; public int nVertex; public int nEdges; public int curEdge; public Graph() {} public void initGraph(int n, int m) { curEdge = 0; nVertex = n; nEdges = m; from = new int[m * 2]; to = new int[m * 2]; first = new int[n]; next = new int[m * 2]; Arrays.fill(first, -1); } public void addEdge(int a, int b) { next[curEdge] = first[a]; first[a] = curEdge; to[curEdge] = b; from[curEdge] = a; ++curEdge; next[curEdge] = first[b]; first[b] = curEdge; to[curEdge] = a; from[curEdge] = b; ++curEdge; } } class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } class Parent { public static int[] run(Graph tree, int root) { int[] parent = new int[tree.nVertex]; int[] queue = new int[tree.nVertex]; int front = 0, back = 0; queue[back++] = root; parent[root] = -1; while (front < back) { int v = queue[front++]; for (int i = tree.first[v]; i != -1; i = tree.next[i]) { if (parent[v] != tree.to[i]) { queue[back++] = tree.to[i]; parent[tree.to[i]] = v; } } } return parent; } public static int getParent(int v, int dst, int[][] parents) { for (int i = 0; i < parents.length; ++i) { if (BitUtils.checkBit(dst, i)) { if (parents[i][v] == -1) return -1; v = parents[i][v]; } } return v; } public static int[][] getLevelParents(Graph tree, int root) { int maxLevel = 1; while ((1 << maxLevel) <= tree.nVertex) { ++maxLevel; } int[][] parent = new int[maxLevel][tree.nVertex]; ArrayUtils.fill(parent, -1); parent[0] = Parent.run(tree, root); for (int level = 1; level < maxLevel; ++level) { for (int i = 0; i < tree.nVertex; ++i) { if (parent[level-1][i] != -1) { int u = parent[level-1][i]; if (parent[level-1][u] != -1) { int v = parent[level-1][u]; parent[level][i] = v; } } } } return parent; } public static int[] getVertexLevels(Graph tree, int root, int[] parent) { int[] queue = new int[tree.nVertex]; int front = 0, back = 0; queue[back++] = root; parent[root] = -1; int[] level = new int[tree.nVertex]; level[root] = 0; while (front < back) { int v = queue[front++]; for (int i = tree.first[v]; i != -1; i = tree.next[i]) { if (parent[v] != tree.to[i]) { queue[back++] = tree.to[i]; level[tree.to[i]] = level[v] + 1; } } } return level; } } class DFSOrder { int[] start; int[] end; public DFSOrder(Graph tree, int root, int[] p) { start = new int[tree.nVertex]; end = new int[tree.nVertex]; buildDfsOrder(tree, root, p); } public int start(int v) { return start[v]; } public int end(int v) { return end[v]; } private void buildDfsOrder(Graph tree, int root, int[] p) { int[] stack = new int[2 * tree.nVertex]; int top = 0; stack[top++] = (root + 1); int time = 0; while (top > 0) { --top; int v = stack[top]; if (v < 0) { v = (-v) - 1; end[v] = time; ++time; } else { --v; start[v] = time++; stack[top++] = -(v+1); for (int i = tree.first[v]; i != -1; i = tree.next[i]) { if (p[v] != tree.to[i]) { stack[top++] = (tree.to[i] + 1); } } } } } } class ArrayUtils { public static void fill(int[][] f, int value) { for (int i = 0; i < f.length; ++i) { Arrays.fill(f[i], value); } } public static int getMax(int[] a) { int result = a[0]; for (int x : a) result = Math.max(result, x); return result; } } class BitUtils { public static boolean checkBit(int mask, int bit) { return (mask & (1 << bit)) > 0; } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
6f171e45c01fd062edfaa0e441504f3d
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.*; import java.util.*; public class BloodCousins { public static int N; public static int D; public static int[][] par; public static int[] depth; public static boolean[] vis; public static ArrayList<Integer>[] adj; public static ArrayList<Integer>[] depths; public static int[] ti, to; public static int time = 0; public static void main(String[] args) throws Exception{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(f.readLine()); adj = new ArrayList[N]; depths = new ArrayList[N]; for(int i = 0; i < N; i ++) { adj[i] = new ArrayList<Integer>(); depths[i] = new ArrayList<Integer>(); } D = Integer.numberOfTrailingZeros(Integer.highestOneBit(N)); par = new int[D+1][N]; depth = new int[N]; ti = new int[N]; to = new int[N]; for(int[] dd:par) { Arrays.fill(dd, -1); } StringTokenizer st = new StringTokenizer(f.readLine()); for(int i = 0; i < N; i ++) { int x = Integer.parseInt(st.nextToken()) - 1; par[0][i] = x; if(x != -1) adj[x].add(i); } for(int i = 0; i < N; i ++) { if(par[0][i] == -1) { dfs(i); } } for(int k=1;k<=D;k++) { for(int i = 0;i<N;i++) { int mid = par[k-1][i]; if(mid != -1) { par[k][i] = par[k-1][mid]; } } } int q = Integer.parseInt(f.readLine()); for(int i = 0; i < q; i ++) { st = new StringTokenizer(f.readLine()); int x = Integer.parseInt(st.nextToken()) - 1; int p = Integer.parseInt(st.nextToken()); System.out.print(solveQuery(x,p) + " "); } } static void dfs(int i) { ti[i] = time ++; for(int x : adj[i]) { depth[x] = depth[i] + 1; depths[depth[x]].add(x); dfs(x); } to[i] = time ++; } static int walk(int i, int k) { for(int d = 0; d <= D && i != -1; d ++) { if(((1 << d) & k) > 0) { i = par[d][i]; } } return i; } static int lca(int i, int j) { if(depth[i] > depth[j]) { i = walk(i,depth[i] - depth[j]); } if(depth[j] > depth[i]) { j = walk(j,depth[j] - depth[i]); } if(i == j) { return i; } for(int d=D;d >=0;d--) { if(par[d][i] != par[d][j]) { i = par[d][i]; j = par[d][j]; } } return par[0][i]; } static int solveQuery(int i, int p) { int x = walk(i,p); if(x == -1) return 0; int left = 0; int right = depths[depth[i]].size() - 1; while(left < right) { int mid = (left + right+1)/2; if(ti[depths[depth[i]].get(mid)] < to[x]) { left = mid; } else { right = mid - 1; } } int rpointer = left; left = 0; right = depths[depth[i]].size() - 1; while(left < right) { int mid = (left + right)/2; if(ti[depths[depth[i]].get(mid)] > ti[x]) { right = mid; } else { left = mid + 1; } } int lpointer = left; return rpointer - lpointer; } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
b71a995067ec0b5fbd9b14a5e5ca444b
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class BloodCousins { static int[] ans; static ArrayList<query>[] qu; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] from = new int[n]; int[] to = new int[n]; for (int i = 0; i < n; i++) { from[i] = sc.nextInt()-1; to[i] = i; } adj = packD(n, from, to); int m = sc.nextInt(); ans = new int[m]; init(n); qu = new ArrayList[n]; for (int i = 0; i < m; i++) { int u = sc.nextInt()-1; int kth = sc.nextInt(); int par = -1; int up = kth; if(lvl[u] >= kth) { par = u; for (int l = lg; l >= 0; l--) { if(up >= 1<<l) { up -= 1<<l; par = a[l][par]; } } } if(par == -1) ans[i] = 0; else { query q = new query(kth + lvl[par], i); if(qu[par] == null) qu[par] = new ArrayList<BloodCousins.query>(); qu[par].add(q); } } sz = new int[n]; cnt = new int[n+2]; for (int i = 0; i < n; i++) if(p[i] == -1) { size(i, -1); solve(i, -1, false); } for (int i = 0; i < ans.length; i++) { if(i != 0) pw.print(" "); pw.print(ans[i]); } pw.println(); pw.flush(); pw.close(); } private static void size(int u, int p) { sz[u] = 1; for (int v : adj[u]) { if(v != p) { size(v, u); sz[u] += sz[v]; } } } static int[] cnt; static void add(int u, int p, int ar, int heavy) { cnt[lvl[u]]+=ar; for (int v : adj[u]) if(v != p && v != heavy) add(v, u, ar, heavy); } static int sz[]; private static void solve(int u, int p, boolean keep) { int mx = -1; int big = -1; for (int v : adj[u]) { if(p == v) continue; if(sz[v] > mx) { mx = sz[v]; big = v; } } for (int v : adj[u]) if(v != p && v != big) solve(v, u, false); if(big != -1) solve(big, u, true); add(u, p, 1, big); if(qu[u] != null) for (query q : qu[u]) ans[q.ind] = cnt[q.l]-1; if(!keep) add(u, p, -1, -1); } static int[] lvl, p, a[]; static int lg = 20; static int[][] adj; static int[] q; static int s, e; static void init(int n) { lvl = new int[n]; p = new int[n]; a = new int[lg+1][n]; q = new int[n]; Arrays.fill(p, -2); for (int i = 0; i < n; i++) if(p[i] == -2) bfs(i); for (int i = 0; i < n; i++) a[0][i] = p[i]; for (int l = 1; l < lg+1; l++) for (int u = 0; u < n; u++) if(lvl[u] >= 1<<l) a[l][u] = a[l-1][a[l-1][u]]; } private static void bfs(int root) { q[e++] = root; p[root] = -1; lvl[root] = 0; for (; s < e;) { int u = q[s++]; for (int v : adj[u]) if(p[u] != v) { p[v] = u; lvl[v] = lvl[u]+1; q[e++] = v; } } } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static class query { int l, ind; public query(int l, int ind) { this.l = l; this.ind = ind; } public String toString() { return ind + ": " + l; } } static class Scanner { StringTokenizer st;BufferedReader br; public Scanner(InputStream s){br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException{br = new BufferedReader(new FileReader(new File((s))));} public String next() throws IOException{while (st == null || !st.hasMoreTokens())st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException{return Integer.parseInt(next());} public long nextLong() throws IOException{return Long.parseLong(next());} public String nextLine() throws IOException{return br.readLine();} public double nextDouble() throws IOException{return Double.parseDouble(next());} public boolean ready() throws IOException{return br.ready();} } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
c26b3894a4f8871a1a98bc949b11ac6e
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class D { static ArrayList<Query>[] queries; static ArrayList<Integer>[] next; static int[] ans, size, cnt; static int findSize(int u) { int sz = 1; for(int v: next[u]) sz += findSize(v); return size[u] = sz; } static void add(int u, int h, int x) { cnt[h]++; for(int v: next[u]) if(v != x) add(v, h + 1, x); } static void erase(int u, int h) { cnt[h]--; for(int v: next[u]) erase(v, h + 1); } static void dfs(int u, int h, boolean keep) { int heavy = -1, max = -1; for(int v: next[u]) if(size[v] > max) max = size[heavy = v]; for(int v: next[u]) if(v != heavy) dfs(v, h + 1, false); if(heavy != -1) dfs(heavy, h + 1, true); add(u, h, heavy); for(Query q: queries[u]) ans[q.idx] = cnt[h + q.k] - 1; if(!keep) erase(u, h); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int[][] P = new int[18][N]; for(int i = 0; i < N; ++i) P[0][i] = sc.nextInt() - 1; for(int k = 1; k < 18; ++k) for(int i = 0; i < N; ++i) P[k][i] = P[k - 1][i] != -1 ? P[k - 1][P[k - 1][i]] : -1; int Q = sc.nextInt(); queries = new ArrayList[N]; next = new ArrayList[N]; for(int i = 0; i < N; ++i) { queries[i] = new ArrayList<Query>(); next[i] = new ArrayList<Integer>(); } for(int i = 0; i < N; ++i) if(P[0][i] != -1) next[P[0][i]].add(i); for(int i = 0; i < Q; ++i) { int v = sc.nextInt() - 1, p = sc.nextInt(); v = getKth(P, p, v); if(v == -1) continue; queries[v].add(new Query(i, p)); } ans = new int[Q]; size = new int[N]; cnt = new int[N]; for(int i = 0; i < N; ++i) if(P[0][i] == -1) { findSize(i); dfs(i, 0, false); } StringBuilder sb = new StringBuilder(); for(int q: ans) sb.append(q + " "); out.println(sb); out.flush(); out.close(); } static int getKth(int[][] P, int k, int u) { for(int i = 17; i >= 0; --i) if(1<<i <= k && P[i][u] != -1) { u = P[i][u]; k ^= 1<<i; } return k == 0 ? u : -1; } static class Query { int idx, k; Query(int a, int b) { idx = a; k = b; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
8116d8b5c97f7b6b6cb3e0ef731c17dd
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.*; import java.util.*; import java.util.Map.Entry; public class TestClass { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; static int n = 0,counter = 0,time = 0; static int parent[],root[],level[],st[],et[],p[][]; static ArrayList<Integer> a[],b[]; public static void dfs(int index,int lev){ st[index] = time++; level[index] = lev; for(int i=0;i<a[index].size();i++) dfs(a[index].get(i),lev+1); et[index] = time-1; } private static void soln(){ n = nI(); parent = new int[n+1]; root = new int[n+1]; level = new int[n+1]; st = new int[n+1]; et = new int[n+1]; a = new ArrayList[n+1]; b = new ArrayList[n+1]; for(int i=0;i<=n;i++){ a[i] = new ArrayList<Integer>(); b[i] = new ArrayList<Integer>(); } for(int i=1;i<=n;i++){ parent[i] = nI(); a[parent[i]].add(i); if(parent[i]==0) root[counter++] = i; } p = new int[n+1][(int)(Math.log10(n)/Math.log10(2))+1]; for(int i=0;i<=n;i++) p[i][0] = parent[i]; dfs(0,0); int dp[] = new int[25]; dp[0] = 1; for(int i=1;i<25;i++) dp[i] = dp[i-1]*2; for(int j=1;dp[j]<=n;j++){ for(int i=0;i<=n;i++) p[i][j] = p[p[i][j-1]][j-1]; } for(int i=0;i<=n;i++) b[level[i]].add(st[i]); for(int i=0;i<=n;i++) Collections.sort(b[i]); int q = nI(); while(q-->0){ int x = nI(),y = nI(); int kl = y; if(level[x]<=y){ pw.print("0 "); continue; } int log = 0; for(;dp[log++]<=y;); log--; for(int i=log;i>=0;i--){ if(y-dp[i]>0){ x = p[x][i]; y-=dp[i]; } } x = parent[x]; pw.print((bs(et[x]+1,level[x]+kl)-bs(st[x],level[x]+kl)-1)+" "); } } public static int bs(int index,int level){ int x = 0,y = b[level].size()-1; if(b[level].get(0)>=index) return 0; while(x<y){ int mid = (x+y)/2; if(b[level].get(mid)<=index) x = mid+1; else y = mid; } if(b[level].get(x)>=index) return x; else return x+1; } public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); soln(); pw.close(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int nI() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nL() { 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; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nLi() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
69de05b33775a64655898598c71d8184
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter wr = new PrintWriter(System.out); int n=sc.nextInt(); int t[]=new int [n]; N=n; adj=new ArrayList[N]; depth=new ArrayList[N]; for(int i=0;i<N;i++) { adj[i]=new ArrayList<>(); depth[i]=new ArrayList<>(); } tin=new int [N]; tout=new int [N]; L=new int[N]; ArrayList<Integer>root=new ArrayList<>(); for(int i=0;i<n;i++) { int v=sc.nextInt()-1; t[i]=v; if(v==-1)root.add(i); else adj[v].add(i); } int q=sc.nextInt(); for(Integer x:root) { dfs(x,-1); } preprocessParents(t); while(q-->0) { int v=sc.nextInt()-1; int p=sc.nextInt(); int H=L[v]-p; if(H<0) { wr.print(0+" "); continue; } int x=kth(v, H); if(x==-1 ) { wr.print(0+" "); }else { ArrayList<Integer>tmp=depth[L[v]]; int z=-Collections.binarySearch(tmp,tin[x])-1; int y=-Collections.binarySearch(tmp,tout[x])-1; wr.print(Math.abs(z-y)-1+" "); } } wr.close(); } static int []tin,tout; static int t; static ArrayList<Integer>adj[]; static ArrayList<Integer>depth[]; static int N, L[], P[][]; static void dfs(int u,int par) { tin[u]=t++; if(par!=-1) L[u]=L[par]+1; depth[L[u]].add(tin[u]); for(int x:adj[u]) { if(x==par )continue; dfs(x,u); } tout[u]=t; } static void preprocessParents(int[] T) { int k = 0; while(1<<k+1 < N) ++k; P = new int[N][k + 1]; for(int i = 0; i < N; i++) Arrays.fill(P[i], -1); for(int i = 0; i < N; ++i) P[i][0] = T[i]; for(int j = 1; j <= k; j++) for(int i = 0; i < N; i++) if(P[i][j-1] != -1) P[i][j] = P[P[i][j-1]][j-1]; } static int kth(int p,int H) { int k = 0; while(1<<k+1 <= L[p]) ++k; for (int i = k; i >= 0; --i) { if (L[p] - (1<<i) >= H ) p = P[p][i]; } return p; } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
b86c9f7da674b247fd1a6e5715060f5a
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.util.*; import java.io.*; public class BloodCousins { static ArrayList<Integer>[] graph; static int[][] bl; // static int[] sz; static int blSz; static int[] depth; static int[] ans; public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = scanner.nextInt(); graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); blSz = Integer.numberOfTrailingZeros(Integer.highestOneBit(N)); bl = new int[N][blSz + 1]; for (int[] dd : bl) Arrays.fill(dd, -1); int rt = -1; for (int i = 0; i < N; i++) { int r = scanner.nextInt()-1; if (r >= 0) { graph[r].add(i); bl[i][0] = r; } } for (int i = 1; i <= blSz; i++) for (int j = 0; j < N; j++) if (bl[j][i - 1] != -1) bl[j][i] = bl[bl[j][i - 1]][i - 1]; //necessary to split queries here in order to avoid an N^2 runtime ArrayList<Pair> queries[] = new ArrayList[N]; for (int i = 0; i < N; i++) queries[i] = new ArrayList<>(); // sz = new int[N]; int M = scanner.nextInt(); ans = new int[M]; Arrays.fill(ans, 1); for (int i = 0; i < M; i++) { int v = scanner.nextInt() - 1; int p = scanner.nextInt(); for (int j = blSz; j >= 0 && v!=-1; j--) { if ((p & (1 << j)) > 0) v = bl[v][j]; } if (v >= 0) queries[v].add(new Pair(i, p)); else ans[i] = 0; } depth = new int[N]; int[] d = new int[N]; for(int i = 0; i < N; i++) { if (bl[i][0] == -1) dfs(i, d, queries); } for (int i = 0; i < M; i++) { if (i > 0) out.print(" "); out.print(ans[i]); } out.flush(); } //Answering queries on dfs since know depth and by subtree you also know root public static void dfs(int cur, int[] d, ArrayList<Pair>[] q) { //preprocessing so we dont double dip disjoint subtrees if (q[cur].size() > 0) { for(Pair query: q[cur]) { ans[query.v] += d[query.d + depth[cur]]; } } for(int edge: graph[cur]) { d[depth[cur]+1]++; depth[edge] = depth[cur] + 1; dfs(edge, d, q); } if (q[cur].size() > 0) { for(Pair query: q[cur]) { ans[query.v] = d[query.d + depth[cur]] - ans[query.v]; } } } public static class Pair { int v, d; public Pair(int vv, int dd) { v = vv; d = dd; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
5ed1c02be6abbac77e9d5ddde941a0c4
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Ds { static int v; static int[][] par; static int[] dist; static int time = 0; static int[] start; static int[] end; static List<List<Integer>> adj = new ArrayList<>(); static List<List<Integer>> cum = new ArrayList<>(); public static void main(String[] args) throws NumberFormatException, IOException { Scanner in = new Scanner(System.in); v = in.nextInt(); for(int i=0; i<=v; i++) { adj.add(new ArrayList<>()); cum.add(new ArrayList<>()); } List<Integer> roots = new ArrayList<>(); for(int i=0; i<v; i++) { int y = in.nextInt()-1; if(y == -1) { roots.add(i); } else { adj.get(y).add(i); adj.get(i).add(y); } } par = new int[21][v]; dist = new int[v]; start = new int[v]; end = new int[v]; for(int i=0; i<=20; i++) { for(int j=0; j<v; j++) { par[i][j] = -1; } } for(int i : roots) { par[0][i] = -1; dfs(i, -1); } int q = in.nextInt(); for(int i=1; i<=20; i++) { for(int j=0; j<v; j++) { if(par[i-1][j] != -1) { par[i][j] = par[i-1][par[i-1][j]]; } } } PrintWriter out = new PrintWriter(System.out); for(int i=0; i<q; i++) { int vert = in.nextInt()-1; int k = in.nextInt(); if(dist[vert] - k < 0) { out.print(0 +" "); continue; } int ancestor = findKthAncestor(vert, dist[vert] - k); int beg = -1; int e = -1; int pos = 0; for(int j=19; j>=0; j--) { int shift = pos + (1 << j); if(beg + shift < cum.get(dist[vert]).size() && cum.get(dist[vert]).get(beg + shift) < start[ancestor]) { beg += shift; } if(e + shift < cum.get(dist[vert]).size() && cum.get(dist[vert]).get(e + shift) <= end[ancestor]) { e += shift; } } out.print(e - beg - 1 + " "); } out.close(); } private static int findKthAncestor(int vert, int k) { for(int i=20; i>=0; i--) { if(par[i][vert] >= 0 && dist[par[i][vert]] >= k) { vert = par[i][vert]; } } return vert; } private static void dfs(int i, int p) { start[i] = time; cum.get(dist[i]).add(time++); for(int n : adj.get(i)) { if(n == p) { continue; } par[0][n] = i; dist[n] = dist[i] + 1; dfs(n, i); } end[i] = time; } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
de01a957474bee8c457d65daa372d5f2
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Iterator; import java.util.TreeMap; public class Main implements Runnable { static final long MOD = 1000000007L; static final long MOD2 = 1000000009L; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } int MAXN = 1000001; ArrayList<Integer> adj[]; int[] dx = {1,-1,0,0}; int[] dy = {0,0,1,-1}; public void run() { //InputReader sc= new InputReader(new FileInputStream("input.txt")); //PrintWriter w= new PrintWriter(new FileWriter("output.txt")); InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); start = new int[n+1]; end= new int[n+1]; depth = new int[n+1]; parent = new int[n+1][21]; adj = new ArrayList[n+1]; for(int i = 1;i <= n;i++) { adj[i] = new ArrayList(); } for(int i = 1;i <= n;i++) { int x = sc.nextInt(); if(x == 0) { parent[i][0] = 0; continue; }else { parent[i][0] = x; } adj[i].add(x); adj[x].add(i); } for(int i = 1;i <= n;i++) { if(parent[i][0] == 0) { dfs(i,0,0); } } for(int j = 1;j <= 20;j++) { for(int i = 1;i <= n;i++) { if(parent[i][j-1] != -1) { parent[i][j] = parent[parent[i][j-1]][j-1]; } } } TreeMap<Integer,ArrayList<Integer>> tmap = new TreeMap(); for(int i = 1;i <= n;i++) { if(!tmap.containsKey(depth[i])) { tmap.put(depth[i],new ArrayList()); } tmap.get(depth[i]).add(start[i]); } for(Integer key: tmap.keySet()) { Collections.sort(tmap.get(key)); } int q = sc.nextInt(); while(q-- > 0) { int v = sc.nextInt(); int p = sc.nextInt(); if(depth[v] < p) { w.print("0 "); }else { ArrayList<Integer> toSearch = tmap.get(depth[v]); for(int i = 0;i < 21;i++) { if(((p>>i) & 1) == 1) { v = parent[v][i]; } } int ele = -(Collections.binarySearch(toSearch,start[v]) + 1); int ele2 = -(Collections.binarySearch(toSearch,end[v]) + 1); w.print(ele2-ele-1 + " "); } } w.close(); } int[] start; int[] end; int time = 0; int[] depth; int[][] parent; void dfs(int curr,int prev,int dep) { depth[curr] = dep; start[curr] = time++; Iterator<Integer> it = adj[curr].iterator(); while(it.hasNext()) { int n = it.next(); if(n != prev) { dfs(n,curr,dep+1); } } end[curr] = time++; } static class Pair implements Comparable<Pair>{ long a; long b; Pair(long a,long b){ this.a = a; this.b = b; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return Long.compare(this.a+this.b,o.a+o.b); } public boolean equals(Object o) { Pair p = (Pair)o; return this.a == p.a && this.b == p.b; } public int hashCode(){ return Long.hashCode(a)*27 + Long.hashCode(b)* 31; } } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
935dff06856aee05c207deed1dc39e49
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { static final int log = 18; static ArrayList<Integer> adjList[], queries[]; static int[] L, P[], queriesValue, ans, size, biggest, cnt, tin, tout, vertex; static int time; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); queries = new ArrayList[n]; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<>(); queries[i] = new ArrayList<>(); } P = new int[n][log]; L = new int[n]; tin = new int[n]; tout = new int[n]; vertex = new int[n]; size = new int[n]; biggest = new int[n]; ArrayList<Integer> roots = new ArrayList<>(); for (int i = 0; i < n; i++) { int p = sc.nextInt() - 1; if (p == -1) roots.add(i); else adjList[p].add(i); } for (int root : roots) dfs(root, root, 0); int m = sc.nextInt(); ans = new int[m]; queriesValue = new int[m]; for (int i = 0; i < m; i++) { int v = sc.nextInt() - 1, p = sc.nextInt(); int anc = findKthAncesstor(v, p); if (anc != -1) queries[anc].add(i); queriesValue[i] = L[v]; } cnt = new int[n]; for (int root : roots) solve(root, 0); for (int x : ans) out.print(x + " "); out.flush(); out.close(); } static void solve(int u, int keep) { for (int v : adjList[u]) if (v != biggest[u] && v != P[u][0]) solve(v, 0); if (biggest[u] != -1) solve(biggest[u], 1); cnt[L[u]]++; for (int v : adjList[u]) { if (v == biggest[u] || v == P[u][0]) continue; for (int i = tin[v]; i <= tout[v]; i++) cnt[L[vertex[i]]]++; } for (int q : queries[u]) ans[q] = cnt[queriesValue[q]] - 1; if (keep == 0) for (int i = tin[u]; i <= tout[u]; i++) cnt[L[vertex[i]]]--; } static void dfs(int u, int p, int level) { P[u][0] = p; L[u] = level; size[u] = 1; vertex[time] = u; tin[u] = time++; for (int i = 1; i < log; i++) P[u][i] = P[P[u][i - 1]][i - 1]; biggest[u] = -1; for (int v : adjList[u]) if (v != p) { dfs(v, u, level + 1); size[u] += size[v]; if (biggest[u] == -1 || size[biggest[u]] < size[v]) biggest[u] = v; } tout[u] = time - 1; } static int findKthAncesstor(int u, int k) { if (k > L[u]) return -1; for (int i = log; i >= 0; i--) if (1 << i <= k) { u = P[u][i]; k -= 1 << i; } return u; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
d7feb2f0422ae9a5a4f7bf61845fe1fb
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.InputStream; import java.lang.*; public class Source { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter ou = new PrintWriter(System.out); MainCode obj = new MainCode(); obj.Solve(in, ou); ou.close(); } } class MainCode { private int n, q; private int[] h; private int[][] p; private List<Integer> Root; private List<Integer>[] adj; private int cnt; private int[] timeIn, timeOut; private List<Integer>[] Vertex; public void Solve(InputReader inp, PrintWriter out) { n = inp.nextInt(); adj = new ArrayList[n]; Root = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) adj[i] = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { int r = inp.nextInt() - 1; if (r == -1) Root.add(i); else adj[r].add(i); } h = new int[n]; p = new int[n][20]; timeIn = new int[n]; timeOut = new int[n]; Vertex = new ArrayList[n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < 20; ++j) p[i][j] = -1; Vertex[i] = new ArrayList<Integer>(); } for (int s: Root) DFS(s); Init(); q = inp.nextInt(); while (q --> 0) { int v = inp.nextInt() - 1; int p = inp.nextInt(); int u = KthParent(v, p); if (u == -1) out.print("0 "); else out.print((Query(u, p) - 1) + " "); } } private void DFS(int u) { timeIn[u] = cnt++; Vertex[h[u]].add(timeIn[u]); for (int v: adj[u]) { p[v][0] = u; h[v] = h[u] + 1; DFS(v); } timeOut[u] = cnt - 1; } private void Init() { for (int j = 1; 1 << j <= n; ++j) for (int i = 0; i < n; ++i) if (p[i][j - 1] != -1) p[i][j] = p[p[i][j - 1]][j - 1]; } private int KthParent(int u, int k) { for (int i = 20; i >= 0; --i) if ((k >> i & 1) == 1) { u = p[u][i]; if (u == -1) return -1; } return u; } private int Count(List<Integer> L, int k) { int l = 0, r = L.size() - 1, res = 0; while (l <= r) { int m = (l + r) >> 1; if (L.get(m) <= k) { res = m + 1; l = m + 1; } else r = m - 1; } return res; } private int Query(int u, int k) { k += h[u]; return Count(Vertex[k], timeOut[u]) - Count(Vertex[k], timeIn[u] - 1); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
d41535a13ea1479d9b17442008b00e4a
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF208E extends PrintWriter { CF208E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF208E o = new CF208E(); o.main(); o.flush(); } int[] next, jj; int $ = 1; int link(int l, int j) { next[$] = l; jj[$] = j; return $++; } int[] ao, dd; int[][] pp; int ln; int[] ll, rr; int time; Integer[] ii; void init(int n, int m) { next = new int[1 + m]; jj = new int[1 + m]; ao = new int[n]; dd = new int[n]; ln = 0; while (1 << ln + 1 < n) ln++; pp = new int[ln + 1][n]; ll = new int[n]; rr = new int[n]; ii = new Integer[n]; for (int i = 0; i < n; i++) ii[i] = i; } void dfs(int i, int d) { dd[i] = d; ll[i] = time++; for (int h = 1; 1 << h <= d; h++) pp[h][i] = pp[h - 1][pp[h - 1][i]]; for (int l = ao[i]; l != 0; l = next[l]) { int j = jj[l]; dfs(j, d + 1); } rr[i] = time; } int find(int n, int d, int l) { int lower = -1, upper = n; while (upper - lower > 1) { int i = (lower + upper) / 2; int i_ = ii[i]; if (dd[i_] < d || dd[i_] == d && ll[i_] < l) lower = i; else upper = i; } return lower; } void main() { int n = sc.nextInt(); init(n, n - 1); for (int i = 0; i < n; i++) { int p = sc.nextInt() - 1; pp[0][i] = p; if (p != -1) ao[p] = link(ao[p], i); } for (int i = 0; i < n; i++) if (pp[0][i] == -1) dfs(i, 0); Arrays.sort(ii, (i, j) -> dd[i] != dd[j] ? dd[i] - dd[j] : ll[i] - ll[j]); int m = sc.nextInt(); while (m-- > 0) { int i = sc.nextInt() - 1; int d = sc.nextInt(); int d_ = dd[i], ans = 0; if (d_ >= d) { for (int h = ln; h >= 0; h--) if (1 << h <= d) { i = pp[h][i]; d -= 1 << h; } ans = find(n, d_, rr[i]) - find(n, d_, ll[i]) - 1; } print(ans + " "); } println(); } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
c112aef4131837abf50d36825f00ea1e
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; @SuppressWarnings("unchecked") public class E208 { int n; ArrayList<Integer>[] vs; ArrayList<Integer>[] depths; int[] first, last, deep; int idx; void dfs(int node, int depth) { first[node] = idx++; deep[node] = depth; depths[depth].add(node); for(int v : vs[node]) dfs(v, depth + 1); last[node] = idx - 1; } int findPar(int child, int depth) { int lo = 0, hi = depths[depth].size() - 1; int childNum = first[child]; while(lo <= hi) { int m = lo + hi >> 1; int node = depths[depth].get(m); int me = first[node]; if(me <= childNum) lo = m + 1; else hi = m - 1; } return depths[depth].get(hi); } int getFirst(int depth, int l, int r) { int lo = 0, hi = depths[depth].size() - 1; while(lo <= hi) { int m = lo + hi >> 1; int node = depths[depth].get(m); int me = first[node]; if(me >= l) hi = m - 1; else lo = m + 1; } return lo; } int getLast(int depth, int l, int r) { int lo = 0, hi = depths[depth].size() - 1; while(lo <= hi) { int m = lo + hi >> 1; int node = depths[depth].get(m); int me = first[node]; if(me <= r) lo = m + 1; else hi = m - 1; } return hi; } public void solve(JoltyScanner in, PrintWriter out) { n = in.nextInt(); vs = new ArrayList[n + 1]; depths = new ArrayList[n + 1]; first = new int[n + 1]; last = new int[n + 1]; deep = new int[n + 1]; for(int i = 0; i < n + 1; ++i) { vs[i] = new ArrayList<>(); depths[i] = new ArrayList<>(); } for(int i = 1; i <= n; ++i) vs[in.nextInt()].add(i); dfs(0, 0); int q = in.nextInt(); while(q-->0) { int v = in.nextInt(); int p = in.nextInt(); int myDepth = deep[v]; int wantedDepth = myDepth - p; if(wantedDepth <= 0) { out.print(0 + " "); continue; } int par = findPar(v, wantedDepth); int l = first[par], r = last[par]; int fi = getFirst(myDepth, l, r), la = getLast(myDepth, l, r); int ans = la - fi + 1; ans--; //it's my cousins... so kill myself out.print(ans + " "); } out.println(); } public static void main(String[] args) { JoltyScanner in = new JoltyScanner(); PrintWriter out = new PrintWriter(System.out); new E208().solve(in, out); out.close(); } static class JoltyScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JoltyScanner() { in = new BufferedInputStream(System.in, BS); } public JoltyScanner(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ 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 long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar(); boolean neg = c=='-'; if(neg)c=nextChar(); boolean fl = c=='.'; double cur = nextLong(); if(fl) return neg ? -cur/num : cur/num; if(c == '.') { double next = nextLong(); return neg ? -cur-next/num : cur+next/num; } else return neg ? -cur : cur; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
cd8888c318e1b0b0af219f27fb2ace4f
train_003.jsonl
1343057400
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (k &gt; 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x &gt; 0).Let's call two people x and y (x ≠ y) p-th cousins (p &gt; 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
256 megabytes
import java.util.*; import java.io.*; /* 6 0 1 1 0 4 4 1 2 1 24 0 1 1 1 2 3 3 3 4 5 6 6 7 7 8 9 9 12 14 15 0 21 22 23 1 12 2 */ public class BloodCousins { static int dfsid; static int[] start,end,depths; static ArrayList<ArrayList<Integer>> sibs; static ArrayList<Integer>[] children; public static void main(String[] args) { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int log = 1; while((n >> log) > 0){ log++; } int[][] P = new int[log][n]; children = new ArrayList[n]; for (int i = 0; i < children.length; i++) { children[i] = new ArrayList<>(); } for(int i =0; i < n; i++){ P[0][i] = in.nextInt()-1; if(P[0][i] != -1){ children[P[0][i]].add(i); } } for(int l = 1; l < log; l++){ for(int i =0;i <n; i++){ if(P[l-1][i] == -1) P[l][i] = -1; else P[l][i] = P[l-1][P[l-1][i]]; } } dfsid = 0; start = new int[n]; end = new int[n]; depths = new int[n]; sibs = new ArrayList<>(); for(int i =0; i < n; i++){ if(P[0][i] == -1){ dfs(i,0); } } int[][] S = new int[log][n]; for(ArrayList<Integer> level : sibs){ for(int i =0;i < level.size()-1; i++){ S[0][level.get(i)] = level.get(i+1); } S[0][level.get(level.size()-1)] = 987654321; } for(int l = 1; l < log; l++){ for(int i =0;i <n; i++){ if(S[l-1][i] == 987654321) S[l][i] = 987654321; else S[l][i] = S[l-1][S[l-1][i]]; } } int m = in.nextInt(); StringBuilder ans = new StringBuilder(); while(m-->0){ int v = in.nextInt()-1; int p = in.nextInt(); int kthpar = getKthPar(P,v,p); //System.out.println("v: " + v + " p: " + p + " kthpar: " + kthpar); if(kthpar == -1){ ans.append("0 "); continue; } //System.out.println(sibs.get(depths[v]) + " start: " +start[kthpar] + " end: " + end[kthpar]); int j1 =getjump(S,sibs.get(depths[v]).get(0),start[kthpar],true); int j2 =getjump(S,sibs.get(depths[v]).get(0),end[kthpar],false); //System.out.println("j1: " + j1 + " j2: " + j2 + " diff: " + (j2-j1)); ans.append((j2-j1)+" "); } System.out.println(ans.toString().trim()); } static int getKthPar(int[][] P, int start, int k){ if(k == 0) return start; int at = start; for(int pow2 = P.length-1; pow2 >= 0 && at != -1; pow2--){ if((1<<pow2) < k){ at= P[pow2][at]; k -= (1<<pow2); } } return at == -1 ? -1 : P[0][at]; } static int getjump(int[][] S, int start, int look, boolean isfirst){ if(start >= look) return 0; int at = start; int ret = 0; for(int pow2 = S.length-1; pow2 >= 0; pow2--){ int peek = S[pow2][at]; if(peek < look){ at= S[pow2][at]; ret += (1<<pow2); } } if(at < look){ if(isfirst) ret++; else if(S[0][at] <= look) ret++; } return ret; } static void dfs(int at, int depth){ start[at] = dfsid++; depths[at] = depth; if(sibs.size() == depth) sibs.add(new ArrayList<Integer>()); sibs.get(depth).add(start[at]); for(int c : children[at]) dfs(c, depth+1); end[at] = dfsid-1; } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(InputStream in){ br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } } }
Java
["6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
2 seconds
["0 0 1 0 0 1 1"]
null
Java 8
standard input
[ "data structures", "binary search", "dfs and similar", "trees" ]
ce58d35343d66b962fb23b9963783acf
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
2,100
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
standard output
PASSED
78ac7c25bcd6d7706e917717d1e7d9ad
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.*; public class Main{ public static void main(String args[]){ Scanner s=new Scanner(System.in); int n=s.nextInt(); int k=s.nextInt(); String str=s.next(); int[] kk=new int[k]; for(int i=0;i<n;i++){ kk[str.charAt(i)-65]++; } Arrays.sort(kk); System.out.println(kk[0]*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
404a1c42e7f18bac11a7f4d65290586c
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; import java.lang.String; public class HelloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int input = in.nextInt(); int input2 = in.nextInt(); String a = in.next(); int[] m = new int[input2]; int min = input; for (int i=0; i< input; i++) { m[(a.charAt(i)-'A')] +=1; } for(int i = 0; i< input2; i++){ if(m[i] < min) min = m[i]; } System.out.println(min * input2); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
0616e70baa996697121934664b9c17e2
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package javaapplication2; import java.util.*; /** * * @author 1 */ public class JavaApplication2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); String s = in.next(); int [] counts = new int[k]; //Посчитать колво каждой буквы for(int i = 0; i < n; i++) { counts[s.charAt(i) - 'A']++; } //Определить минимальное число повторений в хорошей подпоследователь- //ности одной буквы (min) Arrays.sort(counts); //Выводим min * k System.out.println(k * counts[0]); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
fc7f83217bafa05d0fb5bd55b8c8994f
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class Class1 { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int k=input.nextInt(); String s=input.next(); input.close(); int[] rep=new int[k]; for(int i=0;i<n;i++) rep[(int)s.charAt(i)-65]++; int ans=rep[0]; for(int i=1;i<k;i++) { if(rep[i]<ans) ans=rep[i]; } System.out.println(ans*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
4ce0a965039dd19d42ce1dccfc9c9b02
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int k = scan.nextInt(); String str = scan.next(); int min = x; int[] arr = new int[k]; for(int i=0;i<x;i++){ arr[str.charAt(i) - 'A']++; } for(int j=0;j<k;j++){ if(arr[j]<min){ min = arr[j]; } } System.out.println(min*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
4defec95545d1fcdd27578a188bb58d0
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class cf508A{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int k = Integer.parseInt(s[1]); char[] ss = br.readLine().toCharArray(); int[] aa = new int[26]; for(int i=0;i<n;i++) { aa[(int)(ss[i])-65]++; } int min = Integer.MAX_VALUE; for(int i=0;i<k;i++) { min = Math.min(min,aa[i]); } System.out.println(min*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
ef3338e4bad8e73318ac13f01699a1e6
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; public class A { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] cnt = new int[k]; String s = in.next(); for (int i = 0 ; i < n ; i++) { cnt[s.charAt(i) - 'A'] += 1; } int min = Integer.MAX_VALUE; for (int i = 0 ; i < k ; i++) { min = Math.min(min, cnt[i]); } out.println(min * k); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
b96dfbd6a0bc44a150215cfefdf04dfc
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.*; public class hacker { /*FAtt gyi bbhai*/ 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) { new hacker().run(); } void run() { FastReader sc = new FastReader(); // int[] zeroes = {0,0,0}; int n = sc.nextInt(); int k = sc.nextInt(); String str = sc.next(); int[] a = new int[10000]; for(int i=0;i<n;i++) { a[str.charAt(i)-'A']++; } long min = n; if(n>1) { for(int i=0;i<k;i++) { min = Math.min(a[i],min); } } if(n>1) { System.out.println(min*k); } else if(n==1 && k>1) { System.out.println(0); } else if(n==1 && k==1) { System.out.println(1); } } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
2beb6e888cdfd8c3ee133139a0e90d2d
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Prob { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String m = br.readLine(); String temp2[] = m.split(" "); int n = Integer.parseInt(temp2[0]); int k = Integer.parseInt(temp2[1]); String s = br.readLine(); int st[] = new int[k]; for(int i=0;i<n;i++) { st[s.charAt(i)-65]++; } int count =0; count=Integer.MAX_VALUE; for(int i=0;i<k;i++) { if(st[i]<count) count=st[i]; } if(count ==0) System.out.println(count); else System.out.println(count*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
6fd50ad6a083ca765e0ba5e38a3847d1
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
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); AEquality solver = new AEquality(); solver.solve(1, in, out); out.close(); } static class AEquality { public void solve(int testNumber, Scan in, PrintWriter out) { int n = in.scanInt(); int k = in.scanInt(); String str = in.scanString(); int freq[] = new int[26]; int min = 0; for (int i = 0; i < str.length(); i++) { freq[str.charAt(i) - 'A']++; } min = freq[0]; for (int i = 1; i < k; i++) { if (freq[i] < min) { min = freq[i]; } } out.println(min * k); } } 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; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
f2c5e1a54c1df8dede60178c7aa547e2
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.IOException; import java.util.HashMap; import java.util.Scanner; public class Solutions { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < s.length(); i++) { String ss = s.substring(i, i + 1); if (map.get(ss) == null) { map.put(ss, 1); } else { map.put(ss, map.get(ss) + 1); } } int min = n + 1; for (String key : map.keySet()) { if (map.get(key) < min) min = map.get(key); } boolean isOk = true; for (char i = 'A'; i < 'A' + k; i++) { String key = Character.toString(i); if (map.get(key) == null) { isOk = false; break; } } if(isOk) System.out.println(min * k); else System.out.println(0); sc.close(); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
764b6c5fce06ac648c498bfe92768081
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int l = in.nextInt(); int k = in.nextInt(); String n = in.next(); int a[] = new int[26]; for (int i = 0; i < n.length(); i++) { a[n.charAt(i) - 'A']++; } int min = 10000000; for (int i = 0; i < k; i++) { min = Math.min(min, a[i]); } System.out.println(min * k); in.close(); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
d6557388762c3265faa8a024da8607ba
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class _p001038A { static public void main(final String[] args) throws IOException { p001038A._main(args); } //begin p001038A.java static private class p001038A extends Solver{public p001038A(){nameIn="p001038A.in" ;singleTest=true;}int n;int k;String s;@Override protected void solve(){int[]counts =new int[26];s.chars().forEach(c->counts[(int)(c-'A')]++);int min=Arrays.stream(counts ).limit(k).min().getAsInt();pw.println(min*k);}@Override public void readInput() throws IOException{n=sc.nextInt();k=sc.nextInt();if(sc.hasNextLine()){sc.nextLine ();}s=sc.nextLine().trim();}static public void _main(String[]args)throws IOException {new p001038A().run();}} //end p001038A.java //begin net/leksi/contest/Solver.java static private abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected boolean preprocessDebug =false;protected boolean doNotPreprocess=false;protected Scanner sc=null;protected PrintWriter pw=null;private void process()throws IOException{if(!singleTest){int t=lineToIntArray()[0];while(t-->0){readInput();solve();}}else{readInput();solve( );}}abstract protected void readInput()throws IOException;abstract protected void solve()throws IOException;protected int[]lineToIntArray()throws IOException{return Arrays.stream(sc.nextLine().trim().split("\\s+")).mapToInt(Integer::valueOf).toArray ();}protected long[]lineToLongArray()throws IOException{return Arrays.stream(sc.nextLine ().trim().split("\\s+")).mapToLong(Long::valueOf).toArray();}protected String intArrayToString (final int[]a){return Arrays.stream(a).mapToObj(Integer::toString).collect(Collectors .joining(" "));}protected String longArrayToString(final long[]a){return Arrays.stream (a).mapToObj(Long::toString).collect(Collectors.joining(" "));}protected List<Long> longArrayToList(final long[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect (Collectors.toList());}protected List<Integer>intArrayToList(final int[]a){return Arrays.stream(a).mapToObj(Integer::valueOf).collect(Collectors.toList());}protected List<Long>intArrayToLongList(final int[]a){return Arrays.stream(a).mapToObj(Long ::valueOf).collect(Collectors.toList());}protected void run()throws IOException{ boolean done=false;if(nameIn !=null){try{try(FileInputStream fis=new FileInputStream (nameIn);PrintWriter pw0=select_output();){done=true;sc=new Scanner(fis);pw=pw0; process();}}catch(IOException ex){}}if(!done){try(PrintWriter pw0=select_output( );){sc=new Scanner(System.in);pw=pw0;process();}}}private PrintWriter select_output ()throws FileNotFoundException{if(nameOut !=null){return new PrintWriter(nameOut );}return new PrintWriter(System.out);}} //end net/leksi/contest/Solver.java }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
262412a8448a5fa223641371326a961a
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.DataInputStream; import java.io.FileInputStream; //Not Completed public class Sol1 { static final long MD = 1000000007; public static void main(String[] args)throws IOException { Reader in = new Reader(); int n = in.nextInt(); int k = in.nextInt(); String s = in.line().trim(); int a[] = new int[k+1]; for(int i = 1; i <= s.length(); i++){ char ch = s.charAt(i-1); a[(int)ch-64] += 1; } int ans = 0; int min = 0; for(int j = 1; j <= k; j++){ if(a[j] < min || j == 1){ min = a[j]; } } ans = k * min; System.out.println(ans); in.close(); } static void printArr(int arr[]){ System.out.println(Arrays.toString(arr)); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private StringTokenizer st; 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 line() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c = read(); while (c <= ' ') c = read(); do{ if (c == '\n') break; buf[cnt++] = (byte) c; }while ((c = read()) != -1); String s = new String(buf, 0, cnt); return s; } public String str() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == ' ') break; buf[cnt++] = (byte) c; } String s = new String(buf, 0, cnt); return s; } 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; } public int[] nextArr(int n) throws IOException { int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = this.nextInt(); return arr; } 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
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
2a1e87cdfd4a62a63b9074335ad3c861
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.DataInputStream; import java.io.FileInputStream; //Not Completed public class Sol1 { static final long MD = 1000000007; public static void main(String[] args)throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); String s = in.next(); //System.out.println(s); int a[] = new int[k+1]; for(int i = 1; i <= s.length(); i++){ char ch = s.charAt(i-1); a[(int)ch-64] += 1; } int ans = 0; int min = 0; for(int j = 1; j <= k; j++){ if(a[j] < min || j == 1){ min = a[j]; } } ans = k * min; System.out.println(ans); in.close(); } static void printArr(int arr[]){ System.out.println(Arrays.toString(arr)); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private StringTokenizer st; 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 line() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } String s = new String(buf, 0, cnt); return s; } public String str() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == ' ') break; buf[cnt++] = (byte) c; } String s = new String(buf, 0, cnt); return s; } 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; } public int[] nextArr(int n) throws IOException { int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = this.nextInt(); return arr; } 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
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
1194c1a78a56bd763371174e547b733d
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Scanner; public class equality { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int k = scn.nextInt(); String s = scn.next(); int []cnt= new int[26]; for(int i=0;i<n;i++) { cnt[(int)(s.charAt(i)-'A')]++; } long min=Integer.MAX_VALUE; for(int i=0;i<k;i++) { min=Math.min(cnt[i], min); } System.out.println(min*k); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
5a9449823957dc846caf88702ecfd711
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Equality { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); String s =sc.next(); int[] zähler = new int[k]; for(int i= 0; i<k; i++) { zähler[i]=0; } char[] letters = new char[k]; letters[0] = 'A'; if(k>=2) letters[1] = 'B'; if(k>=3) letters[2] = 'C'; if(k>=4) letters[3] = 'D'; if(k>=5) letters[4] = 'E'; if(k>=6) letters[5] = 'F'; if(k>=7) letters[6] = 'G'; if(k>=8) letters[7] = 'H'; if(k>=9) letters[8] = 'I'; if(k>=10) letters[9] = 'J'; if(k>=11) letters[10] = 'K'; if(k>=12) letters[11] = 'L'; if(k>=13) letters[12] = 'M'; if(k>=14) letters[13] = 'N'; if(k>=15) letters[14] = 'O'; if(k>=16) letters[15] = 'P'; if(k>=17) letters[16] = 'Q'; if(k>=18) letters[17] = 'R'; if(k>=19) letters[18] = 'S'; if(k>=20) letters[19] = 'T'; if(k>=21) letters[20] = 'U'; if(k>=22) letters[21] = 'V'; if(k>=23) letters[22] = 'W'; if(k>=24) letters[23] = 'X'; if(k>=25) letters[24] = 'Y'; if(k>=26) letters[25] = 'Z'; for(int i=0; i<k;i++) { for(int v=0;v<n;v++ ) { if(s.charAt(v)==letters[i]) { zähler[i]++; } } } Arrays.sort(zähler); int ergebnis = zähler[0]*k; System.out.println(ergebnis); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
cb61cdaaed4a86f736d1fbf8c11da638
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class Equality { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str=br.readLine(); String[] str1=str.split(" "); int n=Integer.parseInt(str1[0]); int k=Integer.parseInt(str1[1]); str=br.readLine(); char[] ch=str.toCharArray(); HashMap<Character,Integer> hm=new HashMap<Character,Integer>(); for(char c:ch){ if(!hm.containsKey(c)) hm.put(c,1); else hm.put(c,hm.get(c)+1); } if(hm.size()!=k){ System.out.println(0); return; } int min=Integer.MAX_VALUE; int z=0; for(Map.Entry<Character,Integer> entry:hm.entrySet()){ z=entry.getValue(); if(z<min) min=z; } System.out.println(k*min); } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
f6855a961b9d7e153ec393991f20d3e3
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
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 { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s[]=br.readLine().split(" "); int n=Integer.parseInt(s[0]); int k=Integer.parseInt(s[1]); String p=br.readLine(); char x[]=p.toCharArray(); String p1=p,s1=""; while(!p1.isEmpty()){ String a=""+p1.charAt(0); p1=p1.replaceAll(a,""); s1+=a; } if(s1.length()>=k){ char y[]=s1.toCharArray(); int min=100000; for (int i=0;i<y.length ;i++ ){ int c=0; for (int j=0;j<p.length() ;j++ ){ if(y[i]==x[j]) c++; } if(min>c) min=c; } System.out.println((min*s1.length())); }else System.out.println("0"); } catch(Exception e) { return;} } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output
PASSED
a810a357f0f1a547cc61b14a65a00c56
train_003.jsonl
1536248100
You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int len = in.nextInt(); int k = in.nextInt(); String s = in.next(); char[] count = new char[k]; for (int i = 0; i < len; i++) { char c = s.charAt(i); count[c - 'A']++; } int min = 1000001; for (int i : count) { if (min > i) { min = i; } } int ans = 0; for (int i : count) { if (i >= min) { ans += min; } } if (k == 1) { out.print(len); out.close(); } out.print(ans); } } }
Java
["9 3\nACAABCCAB", "9 4\nABCABCABC"]
2 seconds
["6", "0"]
NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.
Java 8
standard input
[ "implementation", "strings" ]
d9d5db63b1e48214d02abe9977709384
The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.
800
Print the only integer — the length of the longest good subsequence of string $$$s$$$.
standard output