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
95d1b07b8dd37cf6a395e39ae9b5b46d
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class B265 { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { int n = nextInt(); int prev = nextInt(), ans = prev + 1; for (int i = 1; i < n; i++) { int cur = nextInt(); ans += Math.abs(prev - cur) + 2; prev = cur; } out.println(ans); out.flush(); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
d660a66649849a9d4ea098b137cb6155
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.*; public class codeforces implements Runnable { private BufferedReader br = null; private PrintWriter pw = null; private StringTokenizer stk = new StringTokenizer(""); public static void main(String[] args) { new Thread(new codeforces()).run(); } public void run() { /* * try { // br = new BufferedReader(new * FileReader("input.txt")); pw = new * PrintWriter("output.txt"); } catch * (FileNotFoundException e) { e.printStackTrace(); } */ br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); solver(); pw.close(); } private void nline() { try { if (!stk.hasMoreTokens()) stk = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException("KaVaBUnGO!!!", e); } } private String nstr() { while (!stk.hasMoreTokens()) nline(); return stk.nextToken(); } private int ni() { return Integer.valueOf(nstr()); } private long nl() { return Long.valueOf(nstr()); } private double nd() { return Double.valueOf(nstr()); } String nextLine() { try { return br.readLine(); } catch (IOException e) { } return null; } private void solver() { int n = ni(); int a[] = new int [n]; for(int i=0; i<n; i++){ a[i] = ni(); } int ans = n + n-1 ; ans += a[0]; for(int i=1; i<n; i++){ ans+= Math.abs(a[i]-a[i-1]); } System.out.println(ans); } private BigInteger nbi() { return new BigInteger(nstr()); } void exit() { System.exit(0); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
bc55941fa79956f97d107a07d94a1f2f
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.util.*; import java.util.StringTokenizer; public class SolutionB { BufferedReader in; StringTokenizer str; PrintWriter out; String SK; String next() throws IOException { while ((str == null) || (!str.hasMoreTokens())) { SK = in.readLine(); if (SK == null) return null; str = new StringTokenizer(SK); } return str.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter("output.txt"); solve(); out.close(); } public static void main(String[] args) throws IOException { new SolutionB().run(); } void solve() throws IOException { int n=nextInt(); int tot=0; int prevH=nextInt(); tot+=prevH+1; for(int i=1;i<n;i++){ int h=nextInt(); tot+=Math.abs(h-prevH)+2; prevH=h; } System.out.println(tot); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
10b98c0d141c6cb651d8e0635c624ff7
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; import java.math.*; public class RoadSideTrees { /** * @param args */ public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int previoush=input.nextInt(); int t=previoush+1; int h; for (int i=1; i<n;i++) { h=input.nextInt(); t=t+Math.abs(previoush-h)+2; previoush=h; } System.out.println(t); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
520ed194adf1f74612b9168994fe715b
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.util.*; public class RoadsideTreesSimp { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(f.readLine()); int prev = 0; int count = 2*n-1; for (int i = 0; i < n; i++) { int h = Integer.parseInt(f.readLine()); count += Math.abs(prev-h); prev = h; } System.out.println(count); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
f58718fba69e95beef9043e3e7e98edd
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { new Main().start(); } public void start()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; //int test=Integer.parseInt(br.readLine()); //int len=Integer.parseInt(br.readLine()); //int x = st.nextToken(); //st = new StringTokenizer(br.readLine()); //int mod = (int)(Math.pow(10,9))+7; //int count = 0; //3^n + 3* ((-1)^n) //System.out.println(mod); /*while(test --> 0){ }*/ int len = Integer.parseInt(br.readLine()); int height[] = new int[len]; for (int i=0; i<len; i++) { height[i] = Integer.parseInt(br.readLine()); } int ans = height[0]; for (int i=1; i<len; i++) { int diff = height[i] - height[i-1]; if(diff >= 0){ ans += diff; } else{ ans += Math.abs(diff); } ans += 1; } ans += len; System.out.println(ans); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
d38f79eb9e3f11e6c7614fa43110c63c
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.*; import java.io.*; public class R162B { Scanner in; PrintWriter out; int n; int a; public void solve() throws IOException { n = in.nextInt(); int cur = in.nextInt(); a = cur + 1; for (int i = 2; i <= n; i++){ int next = in.nextInt(); a += Math.abs(next - cur) + 2; cur = next; } System.out.print(a); } public void run() { try { in = new Scanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] arg) { new R162B().run(); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
4dcd81dbb75f7021f3d6808c0998f05e
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; public class trees { public static void main(String[] a) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(reader.readLine().trim()); int[] h = new int[n]; int before = h[0] = Integer.parseInt(reader.readLine().trim()); int sum = 0; for(int i = 1; i < n; i++) { h[i] = Integer.parseInt(reader.readLine().trim()); sum += Math.abs(h[i]-before); before = h[i]; } writer.println(sum+n+n-1+h[0]); writer.flush(); writer.close(); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
db86047e8210e75147420bec48d90f7f
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; /** * * @author Artem_Mikhalevitch */ public class Solver extends ASolver { private int n; private int[] h; public static void main(String[] args) { Solver s = new Solver(); s.init(); if (s.readData()) { s.writeData(s.solve()); } } @Override public void init() { super.init(); } @Override public boolean readData() { try { n = nextInt(); h = new int[n]; for (int i = 0; i < n; i++) { h[i] = nextInt(); } } catch (IOException ex) { System.out.println(ex.getCause()); System.out.println(ex.getMessage()); return false; } return true; } public long solve() { int time = h[0] + 1;//1st tree+eat+jump for (int i = 0; i < n-1; i++) { time += Math.abs(h[i] - h[i + 1])+2; } return time; } } abstract class ASolver { protected StringTokenizer tokens; protected BufferedReader input; protected PrintWriter output; public void init() { input = new BufferedReader(new InputStreamReader(System.in)); } public abstract boolean readData(); public void writeData(String result) { System.out.println(result); } public void writeData(int result) { System.out.println(result); } public void writeData(long result) { System.out.println(result); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String next() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } public long infinityImitator(long a, long b) { if (a == Long.MIN_VALUE) { return Long.MIN_VALUE; } else { return a + b; } } public int infinityImitator(int a, int b) { if (a == Integer.MIN_VALUE) { return Integer.MIN_VALUE; } else { return a + b; } } public long max(long... a) { long result = Long.MIN_VALUE; for (int i = 0; i < a.length; i++) { result = Math.max(result, a[i]); } return result; } public int max(int... a) { int result = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { result = Math.max(result, a[i]); } return result; } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
d2a97a0a3476f5e5e69ae1ae4ff6302d
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static int[][] dp; public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int result = 0; int cur = 0; for (int i = 0; i < n; i++) { int val = in.nextInt(); result += Math.abs(val - cur); cur = val; result++; if(i + 1 < n){ result++; } } out.println(result); out.close(); } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int pow(int a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } int val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } // static Point minus(Point a, Point b) { // return new Point(a.x - b.x, a.y - b.y); // } // // static Point add(Point a, Point b) { // return new Point(a.x + b.x, a.y + b.y); // } // // static double cross(Point a, Point b) { // return a.x * b.y - a.y * b.x; // // // } // // static class Point { // // int x, y; // // Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public String toString() { // return "Point: " + x + " " + y; // } // } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader(new File("input.txt"))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
44c280747214eee8136e5e839f7d5adc
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; public class RoadsideTrees { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int result = 0; int temp = input.nextInt(); result += temp + 1; int preH = temp; for (int i = 1; i < n; ++i) { temp = input.nextInt(); result += Math.abs(preH - temp) + 2; preH = temp; } System.out.println(result); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
c61cbb1ff85e520d2f10ddbd6727b55e
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.*; public class B265 { public static void main(String[] args){ Scanner br = new Scanner(System.in); int n = br.nextInt(); int pos = 0; int ans = 0; for(int i = 0;i<n;i++){ int cur = br.nextInt(); if(i != 0){ ans++; } if(cur >= pos){ ans+=(cur-pos); pos = cur; } else{ ans+=(pos-cur); pos = cur; } ans++; } System.out.println(ans); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
d5a1ffdceb5ebabc05a049e6d55b580e
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lgsmitty */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { long result = 0; int pos = 0; final int n = in.nextInt(); for (int i = 0; i < n; ++ i){ final int h = in.nextInt(); if (i > 0){ if (pos > h){ result += pos - h + 1; pos = h; } else { ++ result; } } if (pos <= h){ result += h - pos + 1; } pos = h; } out.println(result); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
14d2dd8d08e0b97d3d27879539ff3447
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; public class RoadsideTreesSimple { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] treeH=new int[n]; for (int i = 0; i < n; i++) { treeH[i]=sc.nextInt(); } int secondCnt=0; int nowHeight=0; for (int i = 0; i < n; i++) { if(i==0) {secondCnt+=treeH[0];secondCnt++;nowHeight=treeH[0];} else { secondCnt+=Math.abs(treeH[i]-treeH[i-1]); secondCnt+=2; } } System.out.println(secondCnt); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
015d517890b8f20fbb1b9d3ae62ee56f
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lwc626 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInputReader in = new MyInputReader(inputStream); MyOutputWriter out = new MyOutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, MyInputReader in, MyOutputWriter out) { int n = in.nextInt(); int[] heights = new int[n]; for(int i = 0; i < n; i ++) heights[i] = in.nextInt(); int ret = 0; int nowAt = 0; for(int i = 0; i < n; i ++){ ret += heights[i] - nowAt + 1; if(i > 0) ret += 1; if(i < n - 1){ nowAt = heights[i+1] > heights[i] ? heights[i] : heights[i+1]; if(heights[i+1] < heights[i]) ret += heights[i] - heights[i+1]; } } out.printLine(ret); } } class MyInputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public MyInputReader(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 int nextInt(){ return readInt() ; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class MyOutputWriter { private final PrintWriter writer; public MyOutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public MyOutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
870611482ad216816f1e8ddd83f235ab
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; /** * Works good for CF * @author cykeltillsalu */ public class Prac { //some local config static boolean test = false; static String testDataFile = "testdata.txt"; static String feedFile = "feed.txt"; CompetitionType type = CompetitionType.CF; private static String ENDL = "\n"; // solution private void solve() throws Throwable { int n = iread(); long h = 0; long time = 0; for (int i = 0; i < n; i++) { long t = lread(); time += Math.abs(t-h); h = t; } System.out.println(time + 2*n -1 ); out.flush(); } public int iread() throws Exception { return Integer.parseInt(wread()); } public double dread() throws Exception { return Double.parseDouble(wread()); } public long lread() throws Exception { return Long.parseLong(wread()); } public String wread() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) throws Throwable { if(test){ //run all cases from testfile: BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile)); String readLine = testdataReader.readLine(); int casenr = 0; out: while (true) { BufferedWriter w = new BufferedWriter(new FileWriter(feedFile)); if(!readLine.equalsIgnoreCase("input")){ break; } while (true) { readLine = testdataReader.readLine(); if(readLine.equalsIgnoreCase("output")){ break; } w.write(readLine + "\n"); } w.close(); System.out.println("Answer on case "+(++casenr)+": "); new Prac().solve(); System.out.println("Expected answer: "); while (true) { readLine = testdataReader.readLine(); if(readLine == null){ break out; } if(readLine.equalsIgnoreCase("input")){ break; } System.out.println(readLine); } System.out.println("----------------"); } testdataReader.close(); } else { // run on server new Prac().solve(); } out.close(); } public Prac() throws Throwable { if (test) { in = new BufferedReader(new FileReader(new File(feedFile))); } } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); enum CompetitionType {CF, OTHER}; }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
89ddf3c67cca9c15d7949cb5665f5da9
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; public class Main { static class node implements Comparable<node> { int i; int j; int sum; public node(int i, int j, int sum){ this.i = i; this.j = j; this.sum = sum; } @Override public int compareTo(node o) { return this.sum - o.sum; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sp; int t = Integer.parseInt(br.readLine()); int[] inp = new int [t]; for (int i = 0; i < t; i++) { inp[i] = Integer.parseInt(br.readLine()); } int count = inp[0] + 1; for (int i = 1; i < inp.length; i++) { if(inp[i - 1] > inp[i]){ count += (inp[i - 1] - inp[i]); count += 2; }else if(inp[i-1] < inp[i]){ count += 1; count += (inp[i] - inp[i - 1]); count +=1; }else{ count +=2; } } System.out.println(count); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
cb428a4885d2d52fcacc53d68e51ced8
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; public class Sorter { int max; int[] height; public Sorter() {} long process(){ long sum = 0,currheight=0; for(int i=0;i<max;i++){ if(i>0) sum++; sum+=Math.abs(height[i]-currheight)+1; currheight = height[i]; } return sum; } void reader(){ BufferedReader br = null; try { String currentLine; br = new BufferedReader(new InputStreamReader(System.in)); currentLine = br.readLine(); max = Integer.parseInt(currentLine); height = new int[max]; int count = 0; while(count<max){ currentLine = br.readLine(); height[count] = Integer.parseInt(currentLine); count++; } } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]){ Sorter s = new Sorter(); s.reader(); System.out.println(s.process()); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
3c4ce16bd963c8f1e5101199ecd16b24
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package codeforces160; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author xeyyam */ public class B { public void run(){ InputReader reader = new InputReader(System.in); int n = reader.nextInt(); int ans=0; int nums[] = new int[n+1]; nums[1] = reader.nextInt(); ans = nums[1] + 1; for(int i = 2 ; i<=n ; i++){ nums[i] = reader.nextInt(); if( nums[i] >= nums[i-1] ){ ans += 1 + 1 + nums[i] - nums[i-1]; }else{ ans += 1 + 1 + nums[i-1] - nums[i]; } } System.out.println(ans); } public static void main(String args[]){ new B().run(); } 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()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
d929767753c300b81ae3d10ba2a37d62
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.util.*; public class second { public static void main(String arr[]) { Scanner sc= new Scanner(System.in); int n = sc.nextInt(); int count=0; int last=0; for(int i=0;i<n;i++) { int new1 = sc.nextInt(); count+=Math.abs(new1-last)+1; last=new1; } count+=n; System.out.println(count-1); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
c03d9894d542a0d16a7f02a282e52e4f
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; public class oldpeykan { public static void main(String args[]) { Scanner input =new Scanner(System.in); int n=input.nextInt(); int [] th=new int [n+1]; for(int i=1;i<n+1;i++) th[i]=input.nextInt(); int sec=0; /*sec+=th[0]+1; if(th[0]<th[1]) { sec+=2+th[1]-th[0]; } else if(th[0]>th[1]) { sec+=2+th[0]-th[1]; } else { sec+=2; }*/ for(int j=0;j<n+1;j++) { try { if(th[j]<th[j+1]) { sec+=2+th[j+1]-th[j]; } else if(th[j]>th[j+1]) { sec+=2+th[j]-th[j+1]; } else { sec+=2; } } catch(Exception e){} } System.out.printf("%d",sec-1); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
5055832f902f35ec93c1b74f9ab099c7
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class CodeforcesR162Div2B { public static int[] parseNumbers(String line, int n) { int[] numbers = new int[n]; int idx = 0; for(int i = 0; i < line.length(); i++) { char c = line.charAt(i); if(Character.isDigit(c)) numbers[idx] = 10 * numbers[idx] + (c - '0'); else idx++; } return numbers; } public static void main(String[] args) throws Exception { // System.setIn(new FileInputStream("CodeforcesR162Div2B.in")); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(bf.readLine()); int[] height = new int[N]; for(int i = 0; i < N; i++) height[i] = Integer.parseInt(bf.readLine()); int count = height[0] + N; for(int i = 1; i < N; i++) { count += Math.abs(height[i] - height[i - 1]) + 1; } System.out.println(count); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
7be9fb9cb51b28767d445c7a77fa7d6a
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.*; public class cf265B{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int prev =0; long time =0; int a = sc.nextInt(); time += a+1; prev = a; for(int i=1; i<n; i++) { int h = sc.nextInt(); time += Math.abs(prev-h); time += 2; prev = h; } System.out.println(time); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
ccd92ad605daf3dbd4332a4e16b00c48
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import static java.lang.Math.*; public class Main implements Runnable{ BufferedReader in; PrintWriter out; StringTokenizer tok; void solve( ) throws NumberFormatException, IOException{ int n = readInt( ); int [ ] array = new int [ n ]; for (int i = 0; i < array.length; ++i ) array[ i ] = readInt( ); int ans = 0; for (int i = 0; i < array.length; ++i ) if ( i == 0) ans += array[ i ] + 1; else ans += abs( array[ i ] - array[ i - 1 ] ) + 2; System.out.println( ans ); } public static void main( String ... args ) throws IOException{ new Thread( null, new Main( ), "", 256 * ( 1L << 20 ) ).start( ); } public void run( ) { try { in = new BufferedReader(new InputStreamReader( System.in ) ); out = new PrintWriter( System.out ); tok = new StringTokenizer( "" ); solve( ); in.close( ); out.close( ); } catch ( Throwable e ) { e.printStackTrace( System.err ); throw new RuntimeException( ); } } String readString( ) throws IOException{ while( !tok.hasMoreElements( ) ) { String line = in.readLine( ); if ( line == null ) return null; tok = new StringTokenizer( line ); } return tok.nextToken( ); } int readInt( ) throws NumberFormatException, IOException{ return Integer.parseInt( readString( ) ); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
8c01704a2e5601e5cb4904f8318eab8e
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class B { public static void main(String[] Args) throws IOException { new B().solve(); } static int[] dx_ = { 0, 0, 1, -1 }; static int[] dy_ = { 1, -1, 0, 0 }; ArrayList<Integer>[] graph; int k = 0; // DISCUSS TIME LIMIT EXCEEDED!!!! PROPER DATA STRUCTURE!!! // Use array if possible or the most efficient data structure void solve() throws IOException { int n = si(), a[] = si(n), o = 0, h = 0; for (int i = 0; i < n; i++) { o += (a[i] - h) + 1; // move and eat h = a[i]; if (i + 1 < n) { if (h > a[i + 1]) { o += (h - a[i + 1]); h = a[i + 1]; } o++; } } System.out.println(o); } public boolean equals(LinkedList<Integer> o1, LinkedList<Integer> o2) { // TODO Auto-generated method stub if (o1.size() != o2.size()) return false; else { LinkedList<Integer> o = new LinkedList<Integer>(); o.addAll(o1); o.removeAll(o2); return o.size() == 0; } } LinkedList<Integer> path = new LinkedList<Integer>(); ArrayList<LinkedList<Integer>> cycles = new ArrayList<LinkedList<Integer>>(); void dfs(int now, int[] v) { v[now] = 1; path.addLast(now); for (int to : graph[now]) { if (v[to] == 0) dfs(to, v); } if (path.size() > 2) if (graph[path.getLast()].contains(path.getFirst())) { add(path); } path.removeLast(); } void add(LinkedList<Integer> b) { for (LinkedList<Integer> a : cycles) { if (equals(a, b)) return; } cycles.add((LinkedList<Integer>) b.clone()); } // ----------------------- Library ------------------------ // ----------------------- GRAPH ------------------------ /** * important for speed!!! PrintWriter out=new PrintWriter(new * OutputStreamWriter(System.out)); out.print(...); out.close(); * * @param v */ // leap year is 29 int[] year = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; void initSystem() throws IOException { if (br != null) br.close(); br = new BufferedReader(new InputStreamReader(System.in)); } void initFile() throws IOException { if (br != null) br.close(); br = new BufferedReader(new InputStreamReader(new FileInputStream( "input.txt"))); } void printWriter() { try { PrintWriter pr = new PrintWriter("output.txt"); pr.println("hello world"); pr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void comparator() { Point[] v = new Point[10]; Arrays.sort(v, new Comparator<Point>() { @Override public int compare(Point a, Point b) { if (a.x != b.x) return -(a.x - b.x); return a.y - b.y; } }); } double distance(Point a, Point b) { double dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); } Scanner in = new Scanner(System.in); String ss() { return in.next(); } String sline() { return in.nextLine(); } int si() { return in.nextInt(); } long sl() { return in.nextLong(); } int[] sai(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } return a; } int[] si(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } return a; } String[] ss(int n) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) { a[i] = ss(); } return a; } int[] sai_(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } return a; } BufferedReader br; StringTokenizer tokenizer; { br = new BufferedReader(new InputStreamReader(System.in)); } void tok() throws IOException { tokenizer = new StringTokenizer(br.readLine()); } int toki() throws IOException { return Integer.parseInt(tokenizer.nextToken()); } int[] rint(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = Integer.parseInt(tokenizer.nextToken()); return a; } int[] rint_(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = Integer.parseInt(tokenizer.nextToken()); return a; } String[] rstrlines(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = br.readLine(); } return a; } long tokl() { return Long.parseLong(tokenizer.nextToken()); } double tokd() { return Double.parseDouble(tokenizer.nextToken()); } String toks() { return tokenizer.nextToken(); } String rline() throws IOException { return br.readLine(); } List<Integer> toList(int[] a) { List<Integer> v = new ArrayList<Integer>(); for (int i : a) v.add(i); return v; } static void pai(int[] a) { System.out.println(Arrays.toString(a)); } static int toi(Object s) { return Integer.parseInt(s.toString()); } static int[] dx3 = { 1, -1, 0, 0, 0, 0 }; static int[] dy3 = { 0, 0, 1, -1, 0, 0 }; static int[] dz3 = { 0, 0, 0, 0, 1, -1 }; static int[] dx = { 1, 0, -1, 1, -1, 1, 0, -1 }, dy = { 1, 1, 1, 0, 0, -1, -1, -1 }; static int INF = 2147483647; // =2^31-1 // -8 static long LINF = 922337203854775807L; // -8 static short SINF = 32767; // -32768 // finds GCD of a and b using Euclidian algorithm public int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } static List<String> toList(String[] a) { return Arrays.asList(a); } static String[] toArray(List<String> a) { String[] o = new String[a.size()]; a.toArray(o); return o; } static int[] pair(int... a) { return a; } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
3d796322f16fbb08462d2714b6bffede
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math.*; public class Cf162B { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int val; int i,j,k,l; int ht=0,step=0,pos=0; for(i=0;i<n;i++) { val=Integer.parseInt(br.readLine()); if(ht<val) { step+=val-ht+1; step++; } else { step+=ht-val+1; step++; } ht=val; } System.out.println(step-1); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
a21fd0afc867741de7d696ec538f531b
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i]= s.nextInt(); int r = a[0] + 1; for(int i=1;i<a.length;i++){ if(a[i] > a[i-1]){ r += a[i] - a[i-1] + 1 + 1; }else{ r += a[i-1] - a[i] + 1 + 1 ; } } System.out.println(r); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
2529f81e6b5724237e6e7db4135e9688
train_002.jsonl
1358686800
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h &gt; hi + 1. Compute the minimal time (in seconds) required to eat all nuts.
256 megabytes
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int H[] = new int[n]; for(int i = 0;i<n;i++) { H[i] = scan.nextInt(); } int h = 0; int t = 0; for(int i = 0;i<n-1;i++) { int r = H[i] - h; h+= r; t+= r; t++; if(H[i+1]<h) { r = h-H[i+1]; h-= r; t+= r; } t++; } t+=(H[n-1]-h)+1; System.out.print(t); } }
Java
["2\n1\n2", "5\n2\n1\n2\n1\n1"]
2 seconds
["5", "14"]
null
Java 6
standard input
[ "implementation", "greedy" ]
a20ca4b053ba71f6b2dc05749287e0a4
The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.
1,000
Print a single integer — the minimal time required to eat all nuts in seconds.
standard output
PASSED
241dc320a1a02817a794294a92149618
train_002.jsonl
1346427000
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?
256 megabytes
import java.math.*; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { final int INF = Integer.MAX_VALUE / 2; public void solve(FastReader in, PrintWriter out) throws IOException { int n = in.nextInt(); final int a[] = new int[n + 1], b[] = new int[n + 1]; int c[] = new int[n]; for(int i = 0; i < n; ++i) { a[in.nextInt() - 1] = i; } for(int i = 0; i < n; ++i) { b[in.nextInt() - 1] = i; } for(int i = 0; i < n; ++i) { c[b[i]] = i; } TreeSet<Integer> tr = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { if(a[i] - b[i] != a[j] - b[j]) { return Integer.compare(a[i] - b[i], a[j] - b[j]); } return Integer.compare(i, j); } }); for(int i = 0; i < n; ++i) { tr.add(i); } for(int i = 0; i < n; ++i) { int ans = INF; Integer low = tr.lower(n); Integer hig = tr.higher(n); if(low != null) { ans = Math.min(ans, -(a[low] - b[low] + i)); } if(hig != null) { ans = Math.min(ans, a[hig] - b[hig] + i); } out.println(ans); int tmp = c[i]; tr.remove(tmp); b[tmp] += n; tr.add(tmp); ++b[n]; } } } class FastReader { BufferedReader in; StringBuilder sb = new StringBuilder(); public FastReader(BufferedReader in) { this.in = in; } public String next() throws IOException { sb.setLength(0); while(true) { int c = in.read(); if(c == -1) { return null; } if(" \n\r\t".indexOf(c) == -1) { sb.append((char)c); break; } } while(true) { int c = in.read(); if(c == -1 || " \n\r\t".indexOf(c) != -1) { break; } sb.append((char)c); } return sb.toString(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2\n1 2\n2 1", "4\n2 1 3 4\n3 4 2 1"]
2 seconds
["1\n0", "2\n1\n0\n1"]
null
Java 7
standard input
[]
4b1326b0891571ef8ccb63a3351d1851
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.
2,100
In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
standard output
PASSED
7ac8c122e80ced0bbb0c70ad5e643911
train_002.jsonl
1346427000
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.AbstractCollection; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Crash */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = in.readIntArray(n); int[] b = in.readIntArray(n); PriorityQueue<Pair<Integer, Integer>> plus = new PriorityQueue<Pair<Integer, Integer>>(); PriorityQueue<Pair<Integer, Integer>> minus = new PriorityQueue<Pair<Integer, Integer>>(); int[] value = new int[n]; int[] sign = new int[n]; int[] loc = new int[n]; for (int i = 0; i < n; i ++) { a[i] --; b[i] --; loc[b[i]] = i; } ArrayList<Integer>[] change = new ArrayList[n]; for (int i = 0; i < n; i ++) change[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) { int x = a[i]; value[x] = Math.abs(i - loc[x]); if (loc[x] < i) { sign[x] = 1; plus.offer(new Pair<Integer, Integer>(value[x], x)); change[loc[x] + n - i].add(x); } else { sign[x] = -1; minus.offer(new Pair<Integer, Integer>(value[x], x)); change[loc[x] - i].add(x); } } for (int i = 0; i < n; i ++) change[i].add(b[i]); int[] tt = new int[n]; for (int i = 0; i < n; i ++) tt[a[i]] = i; for (int i = 0; i < n; i ++) { while (! plus.isEmpty()) { Pair<Integer, Integer> tmp = plus.peek(); int x = tmp.second; if (tmp.first + i == Math.abs((loc[x] - i + n) % n - tt[x]) && sign[x] == 1) break; plus.remove(); } while (! minus.isEmpty()) { Pair<Integer, Integer> tmp = minus.peek(); int x = tmp.second; if (tmp.first - i == Math.abs((loc[x] - i + n) % n - tt[x]) && sign[x] == -1) break; minus.remove(); } int t1 = (plus.isEmpty()) ? Integer.MAX_VALUE : plus.peek().first + i; int t2 = (minus.isEmpty()) ? Integer.MAX_VALUE : minus.peek().first - i; out.printLine(Math.min(t1, t2)); for (int x : change[i]) { sign[x] *= -1; value[x] = Math.abs((loc[x] - (i + 1) + n) % n - tt[x]); if (sign[x] == 1) { plus.offer(new Pair<Integer, Integer>(value[x] - (i + 1), x)); } else { minus.offer(new Pair<Integer, Integer>(value[x] + (i + 1), x)); } } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 int[] readIntArray(int length) { int[] res = new int[length]; for (int i = 0; i < length; i ++) res[i] = readInt(); return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Pair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> implements Comparable<Pair<T1, T2>> { public T1 first; public T2 second; public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (!first.equals(pair.first)) return false; if (!second.equals(pair.second)) return false; return true; } public int hashCode() { int result = first.hashCode(); result = 31 * result + second.hashCode(); return result; } public Pair(T1 first, T2 second) { this.first = first; this.second = second; } public int compareTo(Pair<T1, T2> o) { if (first.compareTo(o.first) != 0) return first.compareTo(o.first); return second.compareTo(o.second); } }
Java
["2\n1 2\n2 1", "4\n2 1 3 4\n3 4 2 1"]
2 seconds
["1\n0", "2\n1\n0\n1"]
null
Java 7
standard input
[]
4b1326b0891571ef8ccb63a3351d1851
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.
2,100
In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
standard output
PASSED
3d5d9da9b1ef95aafc38f9cd653ddcf3
train_002.jsonl
1346427000
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, Scanner in, PrintWriter out) { int N = in.nextInt(); int[] A = new int[N]; int[] posA = new int[N]; for(int i = 0; i < N; i++) { A[i] = in.nextInt(); A[i]--; posA[A[i]] = i; } int[] B = new int[N]; int[] posB = new int[N]; for(int i = 0; i < N; i++) { B[i] = in.nextInt(); B[i]--; posB[B[i]] = i; } TreeSet<Pair> left = new TreeSet<Pair>(); TreeSet<Pair> right = new TreeSet<Pair>(); int[] dist = new int[N]; for(int i = 0; i < N; i++) if(posA[i] <= posB[i]) right.add(new Pair(posB[i] - posA[i], i)); else { left.add(new Pair(posA[i] - posB[i], i)); dist[i] = posB[i] - posA[i]; } for(int i = 0; i < N; i++) { int ans = Integer.MAX_VALUE; if(left.size() > 0) ans = Math.min(ans, left.first().val + i); if(right.size() > 0) ans = Math.min(ans,right.first().val - i); out.println(ans); while(right.size() > 0 && right.first().val == i) { int id = right.first().id; right.remove(right.first()); left.add(new Pair(-i, id)); dist[id] = -i; } int id = B[i]; left.remove(new Pair(dist[id], id)); right.add(new Pair(N - 1 - posA[id] + i + 1, id)); } } private class Pair implements Comparable<Pair> { public int val, id; Pair(int a, int b) { val = a; id = b; } public int compareTo(Pair p) { if(val != p.val) return val - p.val; return id - p.id; } } }
Java
["2\n1 2\n2 1", "4\n2 1 3 4\n3 4 2 1"]
2 seconds
["1\n0", "2\n1\n0\n1"]
null
Java 7
standard input
[]
4b1326b0891571ef8ccb63a3351d1851
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.
2,100
In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
standard output
PASSED
997ca1f0423c722c082e439423f90167
train_002.jsonl
1346427000
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.AbstractCollection; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Crash */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = in.readIntArray(n); int[] b = in.readIntArray(n); PriorityQueue<Pair<Integer, Integer>> plus = new PriorityQueue<Pair<Integer, Integer>>(); PriorityQueue<Pair<Integer, Integer>> minus = new PriorityQueue<Pair<Integer, Integer>>(); int[] value = new int[n]; int[] sign = new int[n]; int[] loc = new int[n]; for (int i = 0; i < n; i ++) { a[i] --; b[i] --; loc[b[i]] = i; } ArrayList<Integer>[] change = new ArrayList[n]; for (int i = 0; i < n; i ++) change[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) { int x = a[i]; value[x] = Math.abs(i - loc[x]); if (loc[x] < i) { sign[x] = 1; plus.offer(new Pair<Integer, Integer>(value[x], x)); change[loc[x] + n - i].add(x); } else { sign[x] = -1; minus.offer(new Pair<Integer, Integer>(value[x], x)); change[loc[x] - i].add(x); } } for (int i = 0; i < n; i ++) change[i].add(b[i]); int[] tt = new int[n]; for (int i = 0; i < n; i ++) tt[a[i]] = i; for (int i = 0; i < n; i ++) { while (! plus.isEmpty()) { Pair<Integer, Integer> tmp = plus.peek(); int x = tmp.second; if (tmp.first + i == Math.abs((loc[x] - i + n) % n - tt[x]) && sign[x] == 1) break; plus.remove(); } while (! minus.isEmpty()) { Pair<Integer, Integer> tmp = minus.peek(); int x = tmp.second; if (tmp.first - i == Math.abs((loc[x] - i + n) % n - tt[x]) && sign[x] == -1) break; minus.remove(); } int t1 = (plus.isEmpty()) ? Integer.MAX_VALUE : plus.peek().first + i; int t2 = (minus.isEmpty()) ? Integer.MAX_VALUE : minus.peek().first - i; out.printLine(Math.min(t1, t2)); for (int x : change[i]) { sign[x] *= -1; value[x] = Math.abs((loc[x] - (i + 1) + n) % n - tt[x]); if (sign[x] == 1) { plus.offer(new Pair<Integer, Integer>(value[x] - (i + 1), x)); } else { minus.offer(new Pair<Integer, Integer>(value[x] + (i + 1), x)); } } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 int[] readIntArray(int length) { int[] res = new int[length]; for (int i = 0; i < length; i ++) res[i] = readInt(); return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Pair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> implements Comparable<Pair<T1, T2>> { public T1 first; public T2 second; public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (!first.equals(pair.first)) return false; if (!second.equals(pair.second)) return false; return true; } public int hashCode() { int result = first.hashCode(); result = 31 * result + second.hashCode(); return result; } public Pair(T1 first, T2 second) { this.first = first; this.second = second; } public int compareTo(Pair<T1, T2> o) { if (first.compareTo(o.first) != 0) return first.compareTo(o.first); return second.compareTo(o.second); } }
Java
["2\n1 2\n2 1", "4\n2 1 3 4\n3 4 2 1"]
2 seconds
["1\n0", "2\n1\n0\n1"]
null
Java 7
standard input
[]
4b1326b0891571ef8ccb63a3351d1851
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.
2,100
In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
standard output
PASSED
554df76a28b8246caca490eb261bd3b2
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF187C extends PrintWriter { CF187C() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF187C o = new CF187C(); o.main(); o.flush(); } int[] dsu; int find(int i) { return dsu[i] < 0 ? i : (dsu[i] = find(dsu[i])); } void join(int i, int j) { i = find(i); j = find(j); if (i == j) return; if (dsu[i] > dsu[j]) dsu[i] = j; else { if (dsu[i] == dsu[j]) dsu[i]--; dsu[j] = i; } } static final int INF = 0x3f3f3f3f; int[] next, jj; int l_ = 1; int link(int l, int j) { next[l_] = l; jj[l_] = j; return l_++; } int[] ao; int[] dd, ss, qq; void init(int n, int m) { dsu = new int[n]; next = new int[1 + m * 2]; jj = new int[1 + m * 2]; ao = new int[n]; dd = new int[n]; ss = new int[n]; qq = new int[n]; } boolean check(int s, int t, int[] vv, int k, int q) { Arrays.fill(dsu, -1); Arrays.fill(dd, INF); int head = 0, cnt = 0; for (int h = 0; h < k; h++) { int v = vv[h]; dd[v] = 0; ss[v] = v; qq[head + cnt++] = v; } while (cnt > 0) { int i = qq[head++]; cnt--; for (int l = ao[i]; l != 0; l = next[l]) { int j = jj[l]; if (dd[j] == INF) { dd[j] = dd[i] + 1; ss[j] = ss[i]; qq[head + cnt++] = j; } else if (dd[i] + 1 + dd[j] <= q) join(ss[i], ss[j]); } } return find(s) == find(t); } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); init(n, m); int[] vv = new int[k + 1]; for (int h = 0; h < k; h++) vv[h] = sc.nextInt() - 1; for (int h = 0; h < m; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; ao[i] = link(ao[i], j); ao[j] = link(ao[j], i); } int s = sc.nextInt() - 1; int t = sc.nextInt() - 1; vv[k++] = t; for (int h = 0; h < k - 1; h++) if (vv[h] == t) { k--; break; } int lower = 0, upper = n; while (upper - lower > 1) { int q = (lower + upper) / 2; if (check(s, t, vv, k, q)) upper = q; else lower = q; } println(upper == n ? -1 : upper); } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 8
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
9ab813c91c1062ea8cfa50a4e56e414f
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class C_Round_119_Div1 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); boolean[] check = new boolean[n]; for (int i = 0; i < k; i++) { check[in.nextInt() - 1] = true; } ArrayList<Integer>[] map = new ArrayList[n]; for (int i = 0; i < n; i++) { map[i] = new ArrayList(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; map[a].add(b); map[b].add(a); } int s = in.nextInt() - 1; int t = in.nextInt() - 1; int st = 0; int ed = n; int result = -1; int[] dist = new int[n]; PriorityQueue<Point> q = new PriorityQueue<>(); while (st <= ed) { int mid = (st + ed) >> 1; if (cal(mid, s, t, dist, check, map)) { if (result == -1 || result > mid) { result = mid; } ed = 0; for (int i : dist) { ed = Math.max(i, ed); } ed = Math.min(mid - 1, ed); if(cal(ed,s,t,dist, check,map)){ if (result == -1 || result > ed) { result = ed; } ed = ed - 1; }else{ st = ed + 1; ed = mid - 1; } } else { st = mid + 1; } } out.println(result); out.close(); } public static boolean cal(int mid, int s, int t, int[] dist, boolean[] check, ArrayList<Integer>[] map) { PriorityQueue<Point> q = new PriorityQueue<>(); Arrays.fill(dist, -1); dist[s] = 0; q.add(new Point(0, s)); while (!q.isEmpty()) { Point p = q.poll(); if (dist[p.y] == p.x && p.x + 1 <= mid) { for (int i : map[p.y]) { if (dist[i] == -1 || dist[i] > 1 + p.x) { dist[i] = 1 + p.x; if (check[i]) { dist[i] = 0; } q.add(new Point(dist[i], i)); } } } } return dist[t] != -1; } static class Dist implements Comparable<Dist> { int pos, max, nearest; public Dist(int pos, int max, int nearest) { this.pos = pos; this.max = max; this.nearest = nearest; } @Override public int compareTo(Dist o) { if (max != o.max) { return Integer.compare(max, o.max); } return Integer.compare(nearest, o.nearest); } @Override public String toString() { return "Dist{" + "pos=" + pos + ", max=" + max + ", nearest=" + nearest + '}'; } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 8
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
f82f35cb9dd558a0bff1ba36b9bc8a5c
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
import java.io.*; import java.util.*; public class C implements Runnable { public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); int n = fs.nextInt(), m = fs.nextInt(); int k = fs.nextInt(); boolean[] flag = new boolean[n]; for(int i = 0; i < k; i++) flag[fs.nextInt()-1] = true; ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for(int i = 0; i < m; i++) { int u = fs.nextInt()-1, v = fs.nextInt()-1; adj[u].add(v); adj[v].add(u); } int lo = 1, hi = n-1; int st = fs.nextInt()-1, en = fs.nextInt()-1; int res = -1; int[] dist = new int[n]; for(int bs = 0; bs < 50 && lo <= hi; bs++) { int mid = (lo+hi)/2; Arrays.fill(dist, -1); ArrayDeque<Integer> dq = new ArrayDeque<>(); for(int i = 0; i < n; i++) if(flag[i]) { dq.add(i); dist[i] = 0; } if(!flag[en]) { dist[en] = 0; dq.add(en); } DSU ds = new DSU(n); while(!dq.isEmpty()) { int u = dq.poll(); if(dist[u] == mid) continue; for(int v : adj[u]) { if(dist[v] == -1) { dist[v] = 1 + dist[u]; ds.union(u, v); dq.add(v); } else { if(1+dist[v]+dist[u] <= mid) ds.union(u, v); } } } if(ds.find(st) == ds.find(en)) { res = mid; hi = mid-1; } else { lo = mid+1; } } out.println(res); out.close(); } class DSU { int n; int[] par, rank; DSU(int a) { n = a; par = new int[n]; rank = new int[n]; for(int i = 0; i < n; i++) { par[i] = i; } } int find(int u) { if(par[u] == u) return u; return par[u] = find(par[u]); } void union(int x, int y) { int px = find(x), py = find(y); if(px == py) return; if(rank[px] >= rank[py]) { if(rank[px] == rank[py]) rank[px]++; par[py] = px; } else { par[px] = py; } } } class FastScanner { 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 FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } 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() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } 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; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 8
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
d00834e2470f36ebcd7d454914f7c4e4
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.util.ArrayDeque; import java.io.PrintWriter; import java.io.Writer; import java.util.Queue; import java.util.Collection; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public static final int inf = 100000000; int[] a; ArrayList<Integer>[] g; int get(int x) { if (a[x] == x) return x; return a[x] = get(a[x]); } void uni(int x, int y) { x = get(x); y = get(y); if (x != y) a[x] = y; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] d = new int[n + m]; for (int i = 0; i < d.length; ++i) d[i] = inf; Queue<Integer> q = new ArrayDeque<Integer>(); for (int i = 0; i < k; ++i) { int x = in.nextInt(); --x; d[x] = 0; q.add(x); } a = new int[n + m]; g = new ArrayList[n + m]; for (int i = 0; i < a.length; ++i) { a[i] = i; g[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); --x; --y; g[x].add(n + i); g[n + i].add(y); g[y].add(n + i); g[n + i].add(x); } int s = in.nextInt(); int t = in.nextInt(); --s; --t; d[t] = 0; q.add(t); int res = 1; while (!q.isEmpty() && get(s) != get(t)) { int x = q.poll(); res = d[x] + 1; for (int y : g[x]) { uni(x, y); if (d[y] == inf) { d[y] = d[x] + 1; q.add(y); } } } if (get(s) != get(t)) res = -1; out.printLine(res); } } class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) return -1; } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public String nextToken() { int c = readSkipSpace(); StringBuilder sb = new StringBuilder(); while (!isSpace(c)) { sb.append((char) c); c = read(); } return sb.toString(); } public String next() { return nextToken(); } public String nextLine() { int c = readSkipSpace(); StringBuilder sb = new StringBuilder(); while (c != '\n' && c != -1) { sb.append(c); c = read(); } return sb.toString(); } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } public long nextLong() { long sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10L + (long)(c - '0'); c = read(); } while (!isSpace(c)); res *= sgn; return res; } public double nextDouble() { double sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpace(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } else if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpace(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } else if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } res *= sgn; return res; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 6
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
8d7fcaaa428618210ff470a6eaa72e75
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; /** * @author Roman Elizarov */ public class Round_119_C { public static void main(String[] args) { new Round_119_C().go(); } int n; int m; int k; boolean[] good; int[][] e; int[] ec; int s; int t; void go() { // read input Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); allocate(); for (int i = 0; i < k; i++) good[in.nextInt() - 1] = true; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; add(u, v); add(v, u); } s = in.nextInt() - 1; t = in.nextInt() - 1; // solve int result = solve(); // write result PrintStream out = System.out; out.println(result); } void allocate() { good = new boolean[n]; e = new int[n][2]; ec = new int[n]; } void add(int u, int v) { if (ec[u] >= e[u].length) e[u] = Arrays.copyOf(e[u], e[u].length * 2); e[u][ec[u]++] = v; } int solve() { good[t] = true; q0 = new Q(n); q1 = new Q(n); gf = new boolean[n]; int lo = 1; int hi = n; while (lo < hi) { int q = (lo + hi) / 2; if (can(q)) hi = q; else lo = q + 1; } return lo < n ? lo : -1; } static class Q { int[] queue; int[] dist; boolean[] f; int head; int tail; public Q(int n) { queue = new int[n]; dist = new int[n]; f = new boolean[n]; } void clear() { for (int i = 0; i < tail; i++) f[queue[i]] = false; head = tail = 0; } boolean isEmpty() { return head == tail; } void add(int v, int d) { queue[tail++] = v; dist[v] = d; f[v] = true; } int remove() { return queue[head++]; } } Q q0; Q q1; boolean[] gf; private boolean can(int q) { Arrays.fill(gf, false); q0.clear(); q0.add(s, 0); gf[s] = true; while (!q0.isEmpty()) { q1.clear(); while (!q0.isEmpty()) { int u = q0.remove(); int d = q0.dist[u] + 1; for (int i = 0; i < ec[u]; i++) { int v = e[u][i]; if (!q0.f[v]) { if (good[v] && !gf[v]) { gf[v] = true; q1.add(v, 0); } if (d < q) q0.add(v, d); } } } if (gf[t]) return true; Q tmp = q0; q0 = q1; q1 = tmp; } return false; } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 6
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
67eb19731f671872bd298bdd2d21bdf5
train_002.jsonl
1336663800
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.
256 megabytes
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; import java.util.concurrent.PriorityBlockingQueue; public class Solution{ int n; boolean[]have; Integer[][]g; int s,t; void solve()throws Exception { n=nextInt(); int m=nextInt(); int k=nextInt(); have=new boolean[n]; for(int i=0;i<k;i++) have[nextInt()-1]=true; ArrayList<Integer>[]list=new ArrayList[n]; for(int i=0;i<n;i++) list[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int a=nextInt()-1; int b=nextInt()-1; list[a].add(b); list[b].add(a); } g=new Integer[n][]; for(int i=0;i<n;i++) g[i]=list[i].toArray(new Integer[0]); s=nextInt()-1; t=nextInt()-1; int low=0; int high=n+2; while (high-low>1) { int mid=(low+high)/2; if(can(mid)) high=mid; else low=mid; } System.out.println(high==n+2?-1:high); } private boolean can(int q) { int[]d=new int[n]; Queue<Integer>queue=new LinkedList<Integer>(); for(int i=0;i<n;i++) { d[i]=Integer.MAX_VALUE; } d[s]=0; queue.add(s); while (queue.size()>0 && d[t]==Integer.MAX_VALUE) { int at=queue.remove(); for(int next: g[at]) if(d[next]>d[at]+1 && d[at]!=q) { d[next]=d[at]+1; if(have[next]) d[next]=0; queue.add(next); } } return d[t]!=Integer.MAX_VALUE; } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(new PrintWriter(System.out)); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new Solution().run(); } }
Java
["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"]
2 seconds
["3", "3"]
NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Java 6
standard input
[ "dsu", "dfs and similar" ]
1b336422bb45642d01cc098d953884a6
The first line contains three space-separated integers n, m, k (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive — the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s, t (1 ≤ s, t ≤ n, s ≠ t) — the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s.
2,000
Print on the only line the answer to the problem — the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
standard output
PASSED
52fa918b5a10cd08ba0d1223d29fabc8
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.util.*; public class Codeforces1320A { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i =0 ; i < n ; i++)a[i] = sc.nextInt(); Map<Integer , Long> map = new HashMap<>(); long ans = 0; for(int i = 0 ; i < n ; i++) { int toPut = a[i] - i; map.put(toPut, map.getOrDefault(toPut, 0L) + a[i]); ans = Math.max(ans, map.get(toPut)); } System.out.println(ans); sc.close(); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
4d089befa34937c09d4b83ced10a1ce2
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.StringTokenizer; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.File; import java.lang.*; import java.net.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int cint() { return Integer.parseInt(next()); } long clong() { return Long.parseLong(next()); } double cdouble() { return Double.parseDouble(next()); } String cline() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void print(Object obj){ System.out.println(obj); } static long[] forloop(int n,FastReader f){ long []arr=new long[n]; for(int i=0;i<n;i++){ arr[i]=f.clong(); } return arr; } public static void main(String[] args)throws Exception{ FastReader f=new FastReader(); int n=f.cint(); long []arr=new long [n];long max=0; long []arr1=new long[n]; HashMap<Long,Long> h=new HashMap<Long,Long>(); arr=forloop(n,f); for(int i=0;i<n;i++){ arr1[i]=arr[i]-(long)i-1; if(h.containsKey(arr1[i])){ h.replace(arr1[i],h.get(arr1[i])+arr[i]); if(h.get(arr1[i])>max){ max = h.get(arr1[i]); } } else{ h.put(arr1[i],arr[i]); if(h.get(arr1[i])>max){ max=h.get(arr1[i]); } } } print(max); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
614b5c8502ff70ff1a0d24210736dffd
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class cf1320_Div2_A { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); long[] pre = new long[(int)(2 * 5e5 + 2)]; for (int i = 1; i <= n; i++) { int val = in.nextInt(); pre[val - i + (int)5e5] += val; } long max = 0; for (int i = 0; i <= 2 * (int)(5e5) + 1; i++) { max = Math.max(pre[i], max); } out.println(max); out.close(); } public static void shuffle(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int rPos = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[rPos]; arr[rPos]=temp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } 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(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
7b1125290fa137f9d517cde93d9bb091
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; /* Прокрастинирую */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int INF = (int) (1e9 + 10); static final int MOD = (int) (1e9 + 7); static final int N = (int) (1e6); static final int LOGN = 62; static void solve() { int n = in.nextInt(); int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } long[] cnt = new long[N]; for (int i = 0; i < n; i++) { cnt[b[i] - i + n] += b[i]; } long ans = 0; for (int i = 0; i < N; i++) { ans = Math.max(ans, cnt[i]); } out.println(ans); } public static void main(String[] args) throws FileNotFoundException { in = new FastReader(System.in); // in = new FastReader(new FileInputStream("connect.in")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream("connect.out")); int q = 1; // q = in.nextInt(); while (q-- > 0) { solve(); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
8722ea452a61254a9a2920724f0fc853
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class A1320 { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Reader s = new Reader(); int n = s.i(); long [] arr = s.arrLong(n); HashMap<Long,Long> map = new HashMap<>(); for (int i=0;i<n;i++) { map.put(arr[i]-i,(map.getOrDefault(arr[i]-i,0L)+arr[i])); } Iterator<Long> it = map.keySet().iterator(); long ans = 0L; while (it.hasNext()) { ans = Math.max(ans,map.get(it.next())); } out.println(ans); out.flush(); } public static void shuffle(long[] arr) { int n = arr.length; Random rand = new Random(); for (int i = 0; i < n; i++) { long temp = arr[i]; int randomPos = i + rand.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = temp; } } private static int power(int a, int n) { int result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a); n /= 2; } else { result = (result * a); n--; } } return result; } private static long query(long[] tree, int in, int start, int end, int l, int r) { if (start >= l && r >= end) return tree[in]; if (end < l || start > r) return 0; int mid = (start + end) / 2; long x = query(tree, 2 * in, start, mid, l, r); long y = query(tree, 2 * in + 1, mid + 1, end, l, r); return x + y; } private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) { if (start == end) { tree[in] = val; arr[idx] = val; return; } int mid = (start + end) / 2; if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val); else update(arr, tree, 2 * in, start, mid, idx, val); tree[in] = tree[2 * in] + tree[2 * in + 1]; } private static void build(int[] arr, long[] tree, int in, int start, int end) { if (start == end) { tree[in] = arr[start]; return; } int mid = (start + end) / 2; build(arr, tree, 2 * in, start, mid); build(arr, tree, 2 * in + 1, mid + 1, end); tree[in] = (tree[2 * in + 1] + tree[2 * in]); } private static int power(int a, int n, int p) { int result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a) % p; n /= 2; } else { result = (result * a) % p; n--; } } return result; } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar, numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String s() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long l() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int i() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double d() throws IOException { return Double.parseDouble(s()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = i(); } return ret; } public long[] arrLong(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = l(); } return ret; } } // static class pairLong implements Comparator<pairLong> { // long first, second; // // pairLong() { // } // // pairLong(long first, long second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pairLong p1, pairLong p2) { // if (p1.first == p2.first) { // if(p1.second > p2.second) return 1; // else return -1; // } // if(p1.first > p2.first) return 1; // else return -1; // } // } // static class pair implements Comparator<pair> { // int first, second; // // pair() { // } // // pair(int first, int second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pair p1, pair p2) { // if (p1.first == p2.first) return p1.second - p2.second; // return p1.first - p2.first; // } // } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
6883a3d7465bff9fc43f9c5ccb237182
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; import static java.util.Collections.*; import static java.lang.Math.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class A_Journey_Planning { public static PrintWriter out; public static InputReader in; public static long MOD = (long)1e9+7; public static long[] dp, b; public static void main(String[] args)throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); b = in.nextArrL(n); dp = new long[n]; long ans = -1; Arrays.fill(dp,-1); HashMap<Long,Integer> map = new HashMap<Long,Integer>(); for(int i=n-1;i>=0;i--){ long diff = b[i]-i; dp[i] = b[i]; if(map.containsKey(diff)){ ans = max(ans,dp[map.get(diff)]+b[i]); dp[i] = dp[map.get(diff)]+b[i]; } map.put(diff,i); ans = max(ans,b[i]); } out.println(ans); 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()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArrI(int n) { int[] a=new int[n]; for(int i=0; i<n; i++) a[i]=nextInt(); return a; } public long[] nextArrL(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
cb2081bd07260c176fb34fb6f8416621
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1320A extends PrintWriter { CF1320A() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1320A o = new CF1320A(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int[] bb = new int[n]; Integer[] ii = new Integer[n]; for (int i = 0; i < n; i++) { bb[i] = sc.nextInt(); ii[i] = i; } Arrays.sort(ii, (i, j) -> (bb[i] - i) - (bb[j] - j)); long ans = 0; for (int i = 0, j; i < n; i = j) { long b = 0; j = i; while (j < n && bb[ii[j]] - ii[j] == bb[ii[i]] - ii[i]) b += bb[ii[j++]]; ans = Math.max(ans, b); } println(ans); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
2fdcbef7158152a6f5ce5fc2a6eaf710
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class Journey_Planning { 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) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int n = t.nextInt(); int[] a = new int[n]; HashMap<Integer, Long> map = new HashMap<>(); for (int i = 0; i < n; ++i) { a[i] = t.nextInt(); int val = a[i] - i; if (map.containsKey(val)) { map.put(val, map.get(val) + a[i]); } else { map.put(val, (long) a[i]); } } long max = 0; for (Map.Entry<Integer, Long> entry : map.entrySet()) { max = Math.max(entry.getValue(), max); } o.println(max); o.flush(); o.close(); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
d326477199d701ca56a3f2e0189ae051
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
/*input 6 10 7 1 9 10 15 */ import java.math.*; import java.io.*; import java.util.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static Reader sc=new Reader(); static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); static int max=0; public static void main(String args[])throws IOException { /* * For integer input: int n=inputInt(); * For long input: long n=inputLong(); * For double input: double n=inputDouble(); * For String input: String s=inputString(); * Logic goes here * For printing without space: print(a+""); where a is a variable of any datatype * For printing with space: printSp(a+""); where a is a variable of any datatype * For printing with new line: println(a+""); where a is a variable of any datatype Scanner in = new Scanner(System.in); //all four int[] dr = { 1, 0, -1, 0 }; int[] dc = { 0, 1, 0, -1 }; println("Case #"+k+": "+1+"");//Google */ int n = inputInt(); int[] bb = new int[n]; Integer[] ii = new Integer[n]; for (int i = 0; i < n; i++) { bb[i] = inputInt(); ii[i] = i; } Arrays.sort(ii, (i, j) -> (bb[i] - i) - (bb[j] - j)); long ans = 0; for (int i = 0, j; i < n; i = j) { long b = 0; j = i; while (j < n && bb[ii[j]] - ii[j] == bb[ii[i]] - ii[i]) b += bb[ii[j++]]; ans = Math.max(ans, b); } println(ans+""); bw.flush(); bw.close(); } static void dfs(int src,int par,List<List<Integer>> ls,boolean visit[]) { if(visit[src]) return; visit[src]=true; Iterator<Integer> ite = ls.get(src).listIterator(); while(ite.hasNext()) { int x=ite.next(); if(!visit[x]) { dfs(x,par,ls,visit); } } } public static long pow(long a,long b) { long result=1; while(b>0) { if(b%2==1) result*=a; a*=a; b/=2; } return result; } public static long nCr(long n, long r) { long ans=1; if(r>n-r) { r=n-r; } for(long i=1;i<=r;i++) { ans*=(n-i+1); ans/=i; } return ans; } public static long modulo(long x,long N) { return (x % N + N) %N; } public static long lcm(long a,long b) { return a / gcd(a, b) * b; } public static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } public static int inputInt()throws IOException { return sc.nextInt(); } public static long inputLong()throws IOException { return sc.nextLong(); } public static double inputDouble()throws IOException { return sc.nextDouble(); } public static String inputString()throws IOException { return sc.readLine(); } public static void print(String a)throws IOException { bw.write(a); } public static void printSp(String a)throws IOException { bw.write(a+" "); } public static void println(String a)throws IOException { bw.write(a+"\n"); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
b65929e0610272b2fdf3f96765834e96
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = new int[n]; long[] dp = new long[n]; long ans = 0; TreeMap<Integer, Integer> first = new TreeMap(); for (int i = 0; i < n; i++) a[i] = sc.nextInt(); for (int i = n - 1; i >= 0; i--) { dp[i] = a[i]; Integer nxt = first.get(i - a[i]); if (nxt != null) dp[i] = a[i] + dp[nxt]; first.put(i - a[i], i); ans = Math.max(ans, dp[i]); } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
b7658ae24c2705224ea3bfa706239344
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.util.*; import java.io.*; public class HelloWorld{ public static void main(String []args)throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()), arr[] = new int[n]; HashMap<Integer, Long> mp = new HashMap<>(); StringTokenizer tk = new StringTokenizer(reader.readLine()); for(int i=0; i<n; i++){ int input = Integer.parseInt(tk.nextToken()); mp.put(input-i, mp.getOrDefault(input-i, (long)0)+input); } long ans = Long.MIN_VALUE; for(Long val : mp.values()) ans = Math.max(ans, val); System.out.println(+ans); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
4bd5df0b345adbd9511c4ba71da4b5b9
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class main{ public static void main(String[] args){ Scanner sc= new Scanner(System.in); int n =sc.nextInt(); long[] arr = new long[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextLong(); } HashMap<Long,Long> ans=new HashMap<>(); long max=0; for(int j=1;j<=n;j++){ long putx = j-arr[j-1]; if(ans.containsKey(putx)){ ans.put(putx,ans.get(putx)+arr[j-1]); } else{ ans.put(putx,arr[j-1]); } if(ans.get(putx)>max){ max=ans.get(putx); } } System.out.println(max); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
c44ef2e05757937c803285f59a686d85
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class Contest1 { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[]a = new int[n]; HashMap<Integer,Long>hm = new HashMap<>(); long ans=0; for (int i =0;i<n;i++){ a[i]=sc.nextInt(); int d= a[i]-i; ans=Math.max(ans,a[i]); hm.put(d,hm.getOrDefault(d,0l)+a[i]); ans=Math.max(ans,hm.get(d)); } pw.println(ans); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } 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\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
606b58a2a09e3ce23c01fca7fb5be3dc
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; public class C625C { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Reader sc = new Reader(); int n=sc.nextInt(); long ar[]=new long[n]; long s[]=new long[n]; HashMap<Long,Long> map=new HashMap<Long,Long>(); long max=-1; for(int x=0;x<n;x++) { ar[x]=sc.nextInt(); s[x]=ar[x]-(x+1); if(!map.containsKey(s[x])) { map.put(s[x],ar[x]); } else { long d=map.get(s[x]); d+=ar[x]; map.put(s[x],d); } } for(long d:map.values()) { if(d>max) { max=d; } } out.println(max); out.close(); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
3388f3906e9bd1f3886dc5b1072f2253
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class recc1320a { static BufferedReader __in; static PrintWriter __out; static StringTokenizer input; public static void main(String[] args) throws IOException { __in = new BufferedReader(new InputStreamReader(System.in)); __out = new PrintWriter(new OutputStreamWriter(System.out)); int n = ri(), b[] = ria(n); long ans = 0; Map<Integer, Long> sum = new HashMap<>(); for(int i = 0; i < n; ++i) { sum.put(b[i] - i, sum.getOrDefault(b[i] - i, 0L) + b[i]); ans = max(ans, sum.get(b[i] - i)); } prln(ans); close(); } // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int ni() {return Integer.parseInt(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
aa216c31c99b5738e7dfb302322c9f5f
train_002.jsonl
1583068500
Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 &gt; c_1$$$, then to some other city $$$c_3 &gt; c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k &gt; c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey: $$$c = [1, 2, 4]$$$; $$$c = [3, 5, 6, 8]$$$; $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long a[]=new long[n+1]; for(int i=0;i<n;i++) a[i]=sc.nextLong(); int sum=0; long max=0; HashMap<Long,Long> hm=new HashMap<>(); for(int i=0;i<n;i++) { if(!hm.containsKey(i-a[i])) hm.put(i-a[i],a[i]); else hm.put(i-a[i],hm.get(i-a[i])+a[i]); } for(Map.Entry<Long,Long> entry :hm.entrySet()) { long x=entry.getValue(); if(x>max) max=x; } System.out.println(max); } }
Java
["6\n10 7 1 9 10 15", "1\n400000", "7\n8 9 26 11 12 29 14"]
2 seconds
["26", "400000", "55"]
NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.
Java 11
standard input
[ "dp", "greedy", "math", "sortings", "data structures" ]
aab8d5a2d42b4199310f3f535a6b3bd7
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.
1,400
Print one integer — the maximum beauty of a journey Tanya can choose.
standard output
PASSED
0ceac5dba6b267ff1a838affb742eaa1
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class efficient{ public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); HashMap<Integer,Integer> map = new HashMap<>(); for(int i = 0;i<n;i++){ int ele = s.nextInt(); map.put(ele,i); } int q = s.nextInt(); long vasya = 0; long petya = 0; while(q-->0){ int element = s.nextInt(); int index = map.get(element); vasya += index+1; petya += n-index; } System.out.print(vasya+" "+petya); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
04caff606793cccb0f571973ed933dbd
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.Scanner; public class codefo { public static void main(String[] args) { // TODO Auto-generated method stub Scanner ob =new Scanner(System.in); int n=ob.nextInt(); int a[]=new int[100001]; for(int i=1;i<=n;++i) { int ne=ob.nextInt(); a[ne]=i; } int q=ob.nextInt(); long sum1=0,sum2=0; for(int i=0;i<q;i++) { int qe=ob.nextInt(); sum1+=a[qe]; sum2+=(n+1-a[qe]); } System.out.println(sum1+" "+sum2); ob.close(); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
f1c47a94a164bc17b9cd9623f2d909ec
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.IntStream; import static java.lang.Math.*; import static java.util.Arrays.*; @SuppressWarnings("ALL") public class BEffectiveApproach { public static void main(String[] $) throws IOException { BEffectiveApproach o = new BEffectiveApproach(); o.main(); out.flush(); out.close(); } void main() throws IOException { int n = in.ri(); int[] pos = new int[n + 1]; in.r(); for (int i = 0; i < n; i++) { pos[in.ni()] = i + 1; } long sum1 = 0, sum2 = 0; int m = in.ri(); in.r(); for (int i = 0; i < m; i++) { int q = in.ni(); sum1 += pos[q]; sum2 += n - pos[q] + 1; } out.prln(sum1, sum2); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; //Fast Reader Class /*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; } }*/ //Input fxs static class in { // input static void r() throws IOException { input = new StringTokenizer(rline()); } static int ri() throws IOException { return Integer.parseInt(rline()); } static long rl() throws IOException { return Long.parseLong(rline()); } static double rd() throws IOException { return Double.parseDouble(rline()); } static int[] ria(int n) throws IOException { int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a; } static int[] riam1(int n) throws IOException { int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a; } static long[] ria1i(long n) throws IOException { long[] a = new long[(int) n + 1]; r(); for (int i = 1; i <= n; i++) a[i] = nl(); return a; } static long[] rla(int n) throws IOException { long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a; } static double[] rda(int n) throws IOException { double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a; } static char[] rcha() throws IOException { return rline().toCharArray(); } static ArrayList<Integer> riaa(int n) throws IOException { ArrayList<Integer> a = new ArrayList<>(); r(); for (int i = 0; i < n; i++) a.add(ni()); return a; } static String rline() throws IOException { return __in.readLine(); } static String n() { return input.nextToken(); } static int rni() throws IOException { r(); return ni(); } static int ni() { return Integer.parseInt(n()); } static long rnl() throws IOException { r(); return nl(); } static long nl() { return Long.parseLong(n()); } static double rnd() throws IOException { r(); return nd(); } static double nd() { return Double.parseDouble(n()); } static List<List<Integer>> rg(int n, int m) throws IOException { List<List<Integer>> g = GR.g(n); for (int i = 0; i < m; ++i) GR.c(g, rni() - 1, ni() - 1); return g; } static void rg(List<List<Integer>> g, int m) throws IOException { for (int i = 0; i < m; ++i) GR.c(g, rni() - 1, ni() - 1); } static List<List<Integer>> rdg(int n, int m) throws IOException { List<List<Integer>> g = GR.g(n); for (int i = 0; i < m; ++i) GR.cto(g, rni() - 1, ni() - 1); return g; } static void rdg(List<List<Integer>> g, int m) throws IOException { for (int i = 0; i < m; ++i) GR.cto(g, rni() - 1, ni() - 1); } static List<Set<Integer>> rsg(int n, int m) throws IOException { List<Set<Integer>> g = GR.sg(n); for (int i = 0; i < m; ++i) GR.c(g, rni() - 1, ni() - 1); return g; } static void rsg(List<Set<Integer>> g, int m) throws IOException { for (int i = 0; i < m; ++i) GR.c(g, rni() - 1, ni() - 1); } static List<Set<Integer>> rdsg(int n, int m) throws IOException { List<Set<Integer>> g = GR.sg(n); for (int i = 0; i < m; ++i) GR.cto(g, rni() - 1, ni() - 1); return g; } static void rdsg(List<Set<Integer>> g, int m) throws IOException { for (int i = 0; i < m; ++i) GR.cto(g, rni() - 1, ni() - 1); } static int[][] rim(int n, int m) throws IOException { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { in.r(); for (int j = 0; j < m; j++) { a[i][j] = in.ni(); } } return a; } } //Output fxs static class out { // output static void pr(int i) { __out.print(i); } static void prln(int i) { __out.println(i); } static void pr(long l) { __out.print(l); } static void prln(long l) { __out.println(l); } static void pr(double d) { __out.print(d); } static void prln(double d) { __out.println(d); } static void pr(char c) { __out.print(c); } static void prln(char c) { __out.println(c); } static void pr(char[] s) { __out.print(new String(s)); } static void prln(char[] s) { __out.println(new String(s)); } static void pr(String s) { __out.print(s); } static void prln(String s) { __out.println(s); } static void pr(Object o) { __out.print(o); } static void prln(Object o) { __out.println(o); } static void prln() { __out.println(); } static void pryes() { prln("yes"); } static void pry() { prln("Yes"); } static void prY() { prln("YES"); } static void prno() { prln("no"); } static void prn() { prln("No"); } static void prN() { prln("NO"); } static void pryesno(boolean b) { prln(b ? "yes" : "no"); } ; static void pryn(boolean b) { prln(b ? "Yes" : "No"); } static void prYN(boolean b) { prln(b ? "YES" : "NO"); } static void prln(int... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static void prln(long... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static void prln(double... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static <T> void prln(Collection<T> c) { int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i) ; if (n >= 0) prln(iter.next()); else prln(); } static void h() { prln("hlfd"); flush(); } static void flush() { __out.flush(); } static void close() { __out.close(); } static void prM(int[][] a, int n, int m) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) out.pr(a[i][j] + " "); out.prln(); } } } //Math fxs static class mathx { // math util static int minof(int a, int b, int c) { return min(a, min(b, c)); } static int minof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static long minof(long a, long b, long c) { return min(a, min(b, c)); } static long minof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static int maxof(int a, int b, int c) { return max(a, max(b, c)); } static int maxof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static long maxof(long a, long b, long c) { return max(a, max(b, c)); } static long maxof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static int powi(int a, int b) { if (a == 0) return 0; int ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static long powl(long a, int b) { if (a == 0) return 0; long ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static int fli(double d) { return (int) d; } static int cei(double d) { return (int) ceil(d); } static long fll(double d) { return (long) d; } static long cel(double d) { return (long) ceil(d); } static int gcf(int a, int b) { return b == 0 ? a : gcf(b, a % b); } static long gcf(long a, long b) { return b == 0 ? a : gcf(b, a % b); } static int lcm(int a, int b) { return a * b / gcf(a, b); } static long lcm(long a, long b) { return a * b / gcf(a, b); } static int randInt(int min, int max) { return __rand.nextInt(max - min + 1) + min; } static long mix(long x) { x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31); } } //Array fxs static class ARR { // array util static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = mathx.randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = mathx.randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = mathx.randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; System.arraycopy(a, 0, ans, 0, a.length); return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; System.arraycopy(a, 0, ans, 0, a.length); return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; System.arraycopy(a, 0, ans, 0, a.length); return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; System.arraycopy(a, 0, ans, 0, a.length); return ans; } } //Graph fxs static class GR { // graph util static List<List<Integer>> g(int n) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g; } static List<Set<Integer>> sg(int n) { List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g; } static void c(List<? extends Collection<Integer>> g, int u, int v) { g.get(u).add(v); g.get(v).add(u); } static void cto(List<? extends Collection<Integer>> g, int u, int v) { g.get(u).add(v); } static void dc(List<? extends Collection<Integer>> g, int u, int v) { g.get(u).remove(v); g.get(v).remove(u); } static void dcto(List<? extends Collection<Integer>> g, int u, int v) { g.get(u).remove(v); } } //Utilsx class static class utilX { static int[] subsetSum(int[] nums) { int M = IntStream.of(nums).sum(); int[] m = new int[M + 10]; for (int i = 0; i < M + 10; i++) m[i] = 0; m[0] = 1; for (int num : nums) { for (int j = M; j >= num; j--) { m[j] |= m[j - num]; } } return m; } static int LIS(int[] nums) { int[] m = new int[nums.length]; for (int i = nums.length - 1; i >= 0; i--) { m[i] = 1; for (int j = i + 1; j < nums.length; j++) { if (nums[j] > nums[i]) { m[i] = max(m[i], m[j] + 1); } } } int ans = 0; for (int i = 0; i < nums.length; i++) { ans = max(ans, m[i]); } return ans; } } //Pair Class static class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
938712327dad252a41a0aaa1fbfe689a
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
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 { Scanner input = new Scanner(System.in); int n = input.nextInt(); int a =0; int[] arr = new int[100001]; for(int i =1;i<=n;i++){ a = input.nextInt(); arr[a] = i; } int t = input.nextInt(); long countA =0; long countB =0; while(t>0){ int b = input.nextInt(); countA+=arr[b]; countB+= ((n+1)-arr[b]); t--; } System.out.print(countA+" "); System.out.print(countB); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
6289ce3bdf524d0e3a04f18856754b8c
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
//package codeforces; import java.io.*; import java.util.*; public final class Codeforces { public static void main(String[] args) throws Exception{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); FastReader sc = new FastReader(); //int tc=sc.nextInt(); int n,a[],m,q[]; long ans1=0,ans2=0; HashMap<Integer,Integer>map=new HashMap<>(); n=sc.nextInt(); a=new int[n]; for(int i=0;i<n;i++){a[i]=sc.nextInt();map.put(a[i],i);} m=sc.nextInt(); q=new int[m]; for(int i=0;i<m;i++)q[i]=sc.nextInt(); for(int i=0;i<m;i++) { ans1+=map.get(q[i])+1; ans2+=n-map.get(q[i]); } out.write(ans1+" "+ans2); out.flush(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
7dccc4937d71f78735d506447aec12ec
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class Prob86{ public static void main(String args[]){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; int temp[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); temp[arr[i] - 1] = i; } int m = s.nextInt(); long counta = 0; long countb = 0; for(int i=0;i<m;i++){ int key = s.nextInt(); int index = temp[key-1]; counta += index +1; countb += ((n-1) - index) +1; } System.out.println(""+counta+" "+countb); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
b38e0ffae88782a77157e5e9f1721d1d
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
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 EffectiveApproach { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution sol = new Solution(); sol.solve(in, out); out.close(); } private static class Solution { private void solve(InputReader in, PrintWriter out) { int n=in.ni(); int[] a=in.readArray(n); int m=in.ni(); int[] b=in.readArray(m); int[] distanceFromStart=new int[n+1]; int[] distanceFromEnd=new int[n+1]; for (int i=0; i<n; ++i) distanceFromStart[a[i]]=i+1; int[] aReverse=new int[n]; for (int i=n-1, j=0; i>=0; --i, ++j) aReverse[j]=a[i]; for (int i=0; i<n; ++i) distanceFromEnd[aReverse[i]]=i+1; long aCount=0, bCount=0; for (int i=0; i<m; ++i) aCount+=distanceFromStart[b[i]]; for (int i=0; i<m; ++i) bCount+=distanceFromEnd[b[i]]; out.println(aCount+" "+bCount); } } private static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } private String n() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private int ni() { return Integer.parseInt(n()); } private int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = ni(); return a; } } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
439f7b68e48bec2491c5b5d733d2c1ec
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; import java.math.*; public class Euler { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n = in.nextInt(); Map<Integer,Integer> map = new HashMap<>(); for (int i = 0;i < n; i++) { int x = in.nextInt(); map.put(x, i); } int q = in.nextInt(); long vasya = 0; long patya = 0; for (int i = 0; i < q; i++) { int x = in.nextInt(); int pos = map.get(x); pos++; vasya += pos; patya += (n - pos + 1); } System.out.println(vasya + " " + patya); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
47f7ba6635ab12f404042b9eb04651ae
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { //Fast Reader private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void resetST() { st = null; } 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()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } st = null; return str; } public int[] nextIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = nextDouble(); } return arr; } } public static void main(String[] args) { final FastReader sc = new FastReader(); final PrintWriter pr = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = sc.nextInt(); } long sum1 = 0; long sum2 = 0; int m = sc.nextInt(); int[] b = sc.nextIntArray(m); int[] ind = new int[n + 1]; for (int i = 1; i < n + 1; i++) { ind[a[i]] = i; } for (int i = 0; i < m; i++) { int x = ind[b[i]]; int y = n - x + 1; sum1 += x; sum2 += y; } // pr.println(Arrays.binarySearch(a,4)); pr.println(sum1 + " " + sum2); pr.close(); // write your code here } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
706aacebc31dd14f90f9dabd4d6e3e99
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; public class EffectiveApproach { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String [] args) throws IOException { int n = Integer.parseInt(reader.readLine()); int [] array = Arrays.stream(reader.readLine().split(" ")).map(x -> Integer.parseInt(x)).mapToInt(Integer::intValue).toArray(); int q = Integer.parseInt(reader.readLine()); int [] queries = Arrays.stream(reader.readLine().split(" ")).map(x -> Integer.parseInt(x)).mapToInt(Integer::intValue).toArray(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int index = 0; index < n; index++) { map.put(array[index], index); } long vasyaCount = 0; long petyaCount = 0; for (int index = 0; index < q; index++) { int query = queries[index]; vasyaCount += map.get(query) + 1; petyaCount += n - map.get(query); } System.out.println(vasyaCount + " " + petyaCount); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
aad82b5e99f5e750549cb22333631d69
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class L30P227B_{ public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); HashMap<Integer,Integer> h=new HashMap<Integer,Integer>(); for(int i=1;i<=n;i++){ h.put(in.nextInt(), i); } int q=in.nextInt(); long a=0; long b=0; for(int i=0;i<q;i++){ int temp=h.get(in.nextInt()); a+=temp; b+=n+1-temp; } System.out.println(a+" "+b); in.close(); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
b9a0552930f59599cf033e203fb284c5
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.*; import java.util.*; public class S { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String args[]) throws IOException{ S.init(System.in); int n = S.nextInt(); int q[] = new int[n + 1]; for(int i = 0 ; i < n ; i++) { q[S.nextInt()] = i + 1; } int m = S.nextInt(); long l = 0; long r = 0; for(int i = 0 ; i < m ; i++) { int x = S.nextInt(); l += q[x]; r += n - q[x] + 1; } System.out.println(l + " " + r); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
e955ba58afb06e5baf49408bcc58631f
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class Main{ public static void main(String []args){ Scanner scan=new Scanner(System.in); int arrayLength = scan.nextInt(); int array[] = new int[100001]; for(int i=0;i<arrayLength;i++){ array[scan.nextInt()]= i; } int searchLength = scan.nextInt(); int searchFor[] = new int [searchLength]; long counterA = 0, counterB =0; for (int j = 0; j < searchLength; j++) { int i = array[scan.nextInt()]; counterA += i + 1; counterB += arrayLength - i; } System.out.println(counterA + " " + counterB); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
1dba9a6a3db877318922fdceb72e4888
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class what { public static void main (String[] args) { Scanner l=new Scanner(System.in); int n=l.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=l.nextInt(); int[] b=new int[n+1]; for(int j=0;j<n;j++){ b[a[j]]=j+1; } long count=0; long cou=0; int m=l.nextInt(); for(int k=0;k<m;k++){ int e=l.nextInt(); count+=b[e]; cou+=(n+1-b[e]); } System.out.println(count+" "+cou); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
32b2a7a52d396abf0840d3862fad986d
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class p7 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<n;i++){ int num=s.nextInt(); hm.put(num,i); } int m=s.nextInt(); long v=0; long p=0; for(int i=0;i<m;i++){ int num=s.nextInt(); int idx=-1; if(hm.containsKey(num)){ idx=hm.get(num); } if(idx==-1){ p=n; v=n; } else{ v=v+idx+1; p=p+n-idx; } } System.out.println(v+" "+p); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
127fc3275094111cf9a58a74dc91ce5f
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class EffectiveApproach { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int m=sc.nextInt(); int b[]=new int[m]; for(int i=0;i<m;i++) b[i]=sc.nextInt(); HashMap <Integer, Integer> map1=new HashMap<>(); for(int i=0;i<n;i++) map1.put(a[i], i+1); long sum1=0,sum2=0; for(int i=0;i<m;i++) sum1+= map1.get(b[i]); int c[]=new int[n]; for(int i=0;i<n;i++) c[i]=a[n-i-1]; HashMap <Integer, Integer> map2=new HashMap<>(); for(int i=0;i<n;i++) map2.put(c[i], i+1); for(int i=0;i<m;i++) sum2+= map2.get(b[i]); System.out.println(sum1+" "+sum2); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
12253b0686b545a5206215d5702b3619
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import javax.swing.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.io.*; /* * untitled.java * Copyright 2019 Karan Kanojia <karankanojia@Karans-MacBook-Air.local> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ public class Main{ static Reader scan = new Reader(); static Scanner scanner = new Scanner(System.in); static int MAX = 111111, bit_max = 32, ALPHA_LIMIT = 30, SQRT_BUCKET = 555, lim = 1000000007; static HashMap<Integer, Integer> quickHash = new HashMap<>(); static long watcher = 0; static StringBuffer stringBuffer = new StringBuffer(); static int get_dir(char a){ if(a == 'U' || a == 'R'){return 1;} return -1; } static boolean flag; static long shift(long a, long b){ long count = 0; while(a > 0 && b > 0){ long bita = (a&1), bitb = (b&1); if(bita == 0 && bitb == 0){ count+=0; }else if(bita == 0 && bitb == 1){ count+=0; }else if(bita ==1 && bitb == 0){ flag = true; count+=0; break; }else{ count+= 1; } a = a >>1; b = b >>1; } return count; } static long power(long a, long b){ if(b == 0){return 1;} else if(b == 1){return a%lim;} else { long par = power(a, b/2); par = (par%lim*par%lim)%lim; if(b%2 == 0){return par;} return (par%lim*a%lim)%lim; } } static class bucket{ long answer = Integer.MAX_VALUE; bucket(){} public void push(long a){answer=Long.min(a, answer);} } public static void main(String[] args) throws IOException { int n = scan.nextInt(), index = 0; HashMap<Integer, Integer> map = new HashMap<>(); long a = 0, b = 0; for(int i=0; i<n; i++){ map.put(scan.nextInt(), index++); } int q = scan.nextInt(); for(int i=0; i<q; i++){ int p = scan.nextInt(); a+= map.get(p)+1; b+= n-map.get(p); } System.out.println(a+" "+b); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
8dca0a3d74c7a37275eb86e55e42c9b1
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class EffectiveApproach { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int n = scn.nextInt(); HashMap<Integer ,Integer> map = new HashMap<>(); int[] arr = new int[n]; for(int i = 0 ; i < n ; i++) { arr[i] = scn.nextInt(); map.put(arr[i], i + 1); } int m = scn.nextInt(); long vasya = 0 ; long petya = 0; while(m > 0 ) { int b = scn.nextInt(); int i = map.get(b); vasya += i; petya += (n + 1 - i ); m--; } System.out.println(vasya + " " + petya); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
6065d930fe0ff4549d3c4e6c4734671b
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.Scanner; import java.util.HashMap; import java.util.Map; public class effectiveapproach { private static HashMap<Integer, int[]> indexMap; private static int arrayLength; // create a hashmap<int, int[]> where the int is the query // and the int[] contains the leftmost and rightmost index of the number // saves storage on duplicates, and has a complexity of O(n) for population public static void main(String[] args) { Scanner in = new Scanner(System.in); arrayLength = in.nextInt(); makeMap(in); // printMap(indexMap); int numQueries = in.nextInt(); long[] LRtotals = countComparisons(in, numQueries); in.close(); System.out.println(LRtotals[0] + " " + LRtotals[1]); } private static long[] countComparisons(Scanner in, int numQueries) { long[] LRtotals = new long[2]; for (int i = 0; i < numQueries; i++) { int query = in.nextInt(); int[] locs = indexMap.get(query); LRtotals[0] += locs[0] + 1; LRtotals[1] += arrayLength - locs[1]; } return LRtotals; } // Creates a new HashMap with the number referring to its leftmost and rightmost index private static void makeMap(Scanner in) { indexMap = new HashMap<Integer, int[]>(); for (int i = 0; i < arrayLength; i++) { int thisNum = in.nextInt(); indexMap.merge(thisNum, new int[] {i, i}, (oldIndexes, newIndexes) -> { return new int[] {Math.min(oldIndexes[0], newIndexes[0]), Math.max(oldIndexes[1], newIndexes[1])}; }); } } private static void printMap(HashMap<Integer, int[]> indexMap) { for (Map.Entry e : indexMap.entrySet()) { // System.out.println(e.getKey() + ": (" + ((int[])(e.getValue()))[0] + ", " + ((int[])(e.getValue()))[1] + ")"); } } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
23e3e8441876beda2d61382225b2072b
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int [] arr = new int [n+1]; for (int i = 1 ; i <= n ; i++){ int a = in.nextInt(); arr[a] = i; } int m = in.nextInt(); long approchA = 0; long approchB = 0; for(int i = 0 ; i < m ; i ++){ int b = in.nextInt(); approchA += arr[b]; approchB += (n-arr[b])+1; } System.out.println(approchA +" "+approchB); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
5d9722c083ae42cbe8d74dbec35f39aa
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class codfroc { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] a = new int[n]; HashMap<Integer,Integer> map = new HashMap<>(n); for (int i = 0; i < n; i++) { int num = s.nextInt(); map.put(num,i+1); } long pet = 0; long vas = 0; int m = s.nextInt(); while(m-->0){ int num = s.nextInt(); pet+=map.get(num); vas+=a.length+1 - map.get(num); } System.out.println(pet+" "+vas); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
a60afdbd14e402cdc5d0883a68a8f5d0
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; // DRIVER CODE public class Main { public static void main(String[] args) throws IOException { //Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // CODE HERE final int noOfElement = Integer.parseInt(br.readLine()); final String inputLine1 = br.readLine(); final String[] temp1 = inputLine1.trim().split("\\s+"); final int noOfQueries = Integer.parseInt(br.readLine()); final String inputLine2 = br.readLine(); final String[] temp2 = inputLine2.trim().split("\\s+"); int temp = 0; final Integer[] elementsOfArray = new Integer[100001]; for (int i = 0; i < noOfElement; i++) { temp = Integer.parseInt(temp1[i]); elementsOfArray[temp] = i; } final ArrayList<Integer> searchQueries = new ArrayList<>(); for (int i = 0; i < noOfQueries; i++) { searchQueries.add(Integer.parseInt(temp2[i])); } long index; long countOfQueryFromFirst, countOfQueryFromSecond; countOfQueryFromFirst = countOfQueryFromSecond = 0; for (int i = 0; i < noOfQueries; i++) { index = elementsOfArray[searchQueries.get(i)]; countOfQueryFromFirst = countOfQueryFromFirst + 1 + index; countOfQueryFromSecond = countOfQueryFromSecond + noOfElement - index; } System.out.println(countOfQueryFromFirst + " " + countOfQueryFromSecond); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
c223794a87dcad2a5f708387b4810512
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.*; import java.util.*; public class Main{ // public static int petyaLS(int a[],int key){ // int comparisons=0; // for (int i=a.length-1;i>-1;i--) { // comparisons++; // if (a[i]==key) return comparisons; // } // return comparisons; // } // public static int vasyaLS(int a[],int key){ // int comparisons=0; // for (int i=0;i<a.length;i++) { // comparisons++; // if (a[i]==key) return comparisons; // } // return comparisons; // } public static void main(String[] args)throws Exception{ //StringTokenizer st;//! @ % & * () _ {} # ~ : < > ? "" | ^ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //StringTokenizer st=new StringTokenizer(br.readLine()); StringTokenizer st; //int a,i=0,b,ans,rem; // int x=Integer.parseInt(st.nextToken()); int n=Integer.parseInt(br.readLine()); //int d=Integer.parseInt(br.readLine()); long vasya=0,petya=0; // while(t-->0) { // boolean primes[]=new boolean[1000001]; // primes[0]=primes[1]=true; // for (int i=2;i*i<primes.length;i++) { // if (!primes[i]) { // //l.add(i); // for (int j=i*i;j<primes.length ;j+=i) { // primes[j]=true; // } // } // } int hv[]=new int[n+1]; int hp[]=new int[n+1]; for (int i=0;i<hp.length;i++){ hv[i]=hp[i]=-1; } //long n=Long.parseLong(br.readLine()); st=new StringTokenizer(br.readLine()); //int s=Integer.parseInt(br.readLine()); //int np=Integer.parseInt(st.nextToken()); int a[]=new int[n]; for (int i=0;i<n ;i++){ a[i]=Integer.parseInt(st.nextToken()); if (hv[a[i]]==-1) hv[a[i]]=i+1; hp[a[i]]=n-i; } int m=Integer.parseInt(br.readLine()); st=new StringTokenizer(br.readLine()); for (int i=0;i<m;i++){ int x=Integer.parseInt(st.nextToken()); vasya+=hv[x]==-1?n:hv[x]; petya+=hp[x]==-1?n:hp[x]; } //String str1 =br.readLine().trim(); // String str1 =br.readLine().trim(); // String str2 =br.readLine().trim(); // String num2 =br.readLine().trim(); //int a[]=new int[n]; //int min=110,max=0,mini=0,maxi=0; // boolean k=false; //Set<Character> s=new HashSet<>(); // for (int i=0;i<str1.length();i++) { // //st=new StringTokenizer(br.readLine()); // if (str1.charAt(i)=='H' || str1.charAt(i)=='Q' ||str1.charAt(i)=='9' ) { // k=true;break; // } // } // for (int i=0;i<str1.length();i++) { // //st=new StringTokenizer(br.readLine()); // h[str1.charAt(i)-65]++; // } // for (int i=0;i<str2.length();i++) { // //st=new StringTokenizer(br.readLine()); // h1[str2.charAt(i)-65]++; // } // for (int i=0;i<h.length;i++) { // //st=new StringTokenizer(br.readLine()); // if (h[i]!=h1[i]) { // k=true;break; // } // } //ans=Math.min(left0,n-left0)+Math.min(right0,n-right0); // String res=""; // int h[]=new int[4]; // //st=new StringTokenizer(br.readLine()); // if (mini<maxi) { // System.out.println(maxi+a.length-mini-2); // } // else //System.out.println(4-s.size()); // for (int i=1;i<h.length;i++ ) { // while(h[i]-->0) { // if (res.length()==0) res+=i; // else res+="+"+i; // } // } // // int i=n+1; // while(i<primes.length && primes[i]){ // i++; // } //if (x>1) ans++; //} // ans=Math.min((l*k)/(n*nl),(c*d)/n); // ans=Math.min(ans,p/(n*np)); // System.out.println(ans); // if (k) System.out.println(vasya+" "+petya); // else System.out.println("NO"); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
b9ea22d7471233dea932f389f29e513a
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class dice{ public static void main(String args[]){ int n; Scanner scan = new Scanner(System.in); n=scan.nextInt(); int A[] = new int[n]; for(int i=0;i<n;i++){ A[i]=scan.nextInt(); } HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<n;i++){ if(!map.containsKey(A[i])) map.put(A[i],i+1); } int B[]= new int[n]; for(int i=0;i<n;i++){ B[i]=A[n-1-i]; } HashMap<Integer,Integer> map2=new HashMap<>(); for(int i=0;i<n;i++){ if(!map2.containsKey(B[i])) map2.put(B[i],i+1); } long l1=0,l2=0; int que=scan.nextInt(); while(que--!=0){ int key=scan.nextInt(); l1+=map.get(key); l2+=map2.get(key); } System.out.print(l1+" "); System.out.print(l2); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
5f021ae84fff437d636174d8da0f87e1
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.Scanner; public class CodeForces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n+1]; for(int i=1;i<n+1;i++) { int x =sc.nextInt(); a[x] = i; } int m = sc.nextInt(); long vas=0,pet=0; for(int i=0;i<m;i++) { int y = sc.nextInt(); vas+=a[y]; pet+=n-a[y]+1; } System.out.println(vas+" "+pet); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
99b59b2cd90f50299fda91f381decea3
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.Scanner; public class test { public static void main(String[] args) { Scanner input =new Scanner(System.in); int n=input.nextInt(); long[] arr=new long [100000+3]; long count1=0,count2=0; int num; for (int i = 0; i < n; i++) { num=input.nextInt(); arr[num]=i+1; } int m=input.nextInt(); int q; for (int i = 0; i < m; i++) { q=input.nextInt(); count1+=arr[q]; count2+=n-arr[q]+1; } System.out.print(count1+" "+count2); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
c5f99175338cb5ebff4ba7f557372f09
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int n = in.nextInt(); // int[] a = new int[n]; int[] indices = new int[n + 1]; for (int i = 0; i < n; i++) { int num = in.nextInt(); // a[i] = num; indices[num] = i; } int m = in.nextInt(); long v = 0; long p = 0; for (int i = 0; i < m; i++) { int num = in.nextInt(); v += indices[num] + 1; p += n - indices[num]; } System.out.println(v + " " + p); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
a7d4c29ed093c954d08a87bf39d53f50
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader scn = new Reader(); StringBuilder res = new StringBuilder(); int n = scn.nextInt(); int[] arr = new int[n + 1]; for (int i = 1; i <= n; i++) { arr[i] = scn.nextInt(); } int m = scn.nextInt(); int[] b = new int[m]; for (int i = 0; i < b.length; i++) { b[i] = scn.nextInt(); } int[] indexes = new int[n + 1]; for (int i = 1; i <= n; i++) { indexes[arr[i]] = i; } long vop = 0; long pop = 0; for (int num : b) { vop += indexes[num]; pop += n + 1 - indexes[num]; } res.append(vop + " " + pop); System.out.print(res); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
b3195a12754edcd07f676046c274ccef
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
//package cp; import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int a[] = sc.readArray(n); int m = sc.nextInt(); long v = 0; long p = 0; HashMap<Integer,Integer> map = new HashMap<>(); for(int i=0 ; i<n ; i++) { map.put(a[i],i+1); } while(m-- >0) { int b = sc.nextInt(); int index = map.get(b); v+=index; p+=(n - index + 1); } System.out.println(v+" "+p); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int [] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
883b9b3bc75203ba1b3d4b3ed2f5bb81
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.*; public class Main { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { // write your code here int n = scanner.nextInt(); int arr[] = new int[100001]; for(int i = 1 ; i<= n ; i++){ arr[scanner.nextInt()] = i; } long CountV = 0; long Countp = 0; int queries = scanner.nextInt(); while(queries > 0){ int query = scanner.nextInt(); CountV += arr[query]; Countp += (n + 1 - arr[query]); queries--; } System.out.println(CountV + " " + Countp); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
eb226e3e37f5e7b6dfa91aff38957acb
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Codeforces227B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { map.put(in.nextInt(), i + 1); } int claims = in.nextInt(); long vasya = 0; long petya = 0; for (int i = 0; i < claims; i++) { int cur = in.nextInt(); vasya += map.get(cur); petya += n - map.get(cur) + 1; } System.out.println(vasya + " " + petya); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
c5c8c04e122bd019b040b94a7378c733
train_002.jsonl
1348500600
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { int n, m; long v=0, p=0; Map<Integer, Integer> as = new HashMap<>(); Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); for (int i = 0 ; i < n ; i++) { as.put(scanner.nextInt(), i); } m = scanner.nextInt(); for (int i = 0 ; i < m ; i++) { int k = as.get(scanner.nextInt()); v += k + 1; p += n - k; } System.out.println(v + " " + p); } }
Java
["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"]
2 seconds
["1 2", "2 1", "6 6"]
NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Java 11
standard input
[ "implementation" ]
b7aef95015e326307521fd59d4fccb64
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array. The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.
1,100
Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
PASSED
9984abe5b82d2a4c4dd875fe6b983e0c
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { static int INF = Integer.MAX_VALUE; public static void main(String[] args)throws IOException { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); int[] small = new int[n]; Arrays.fill(small, INF); Game[] edges = new Game[m]; for (int i=0;i<m;i++) edges[i] = new Game(in.nextInt() - 1, in.nextInt() - 1, in.nextInt()); Arrays.sort(edges); int[] dp = new int[n]; int ans = 0; int[] aux = new int[n]; for (int i=0;i<m;i++) { int j = i + 1; while (j < m && edges[j].w == edges[i].w) j++; for (int k=i;k<j;k++) { Game g = edges[k]; int x = g.a; int y = g.b; aux[x] = Math.max(aux[x], dp[y] + 1); } for (int k=i;k<j;k++) { int x = edges[k].a; int y = edges[k].b; dp[x] = Math.max(dp[x], aux[x]); aux[x] = 0; } i = j - 1; } for (int i=0;i<n;i++) ans = Math.max(ans, dp[i]); System.out.println(ans); } } class Game implements Comparable<Game> { int a; int b; int w; public Game(int a, int b, int w) { this.a = a; this.b = b; this.w = w; } @Override public int compareTo(Game ob) { return ob.w - this.w; } } class Point { long x; long y; public Point(long x, long y) { this.x = x; this.y = y; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
02505226303481e823f4da266c2e0319
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.io.*; public class PashmakandGraph { /************************ SOLUTION STARTS HERE ************************/ private static void solve() { int V = nextInt(); int E = nextInt(); int edges[][] = new int[E][]; for(int i = 0; i < E; i++) edges[i] = nextIntArray(3); Arrays.sort(edges , (e1 , e2) -> e1[2] - e2[2]); int DP[] = new int[V + 1]; int aux[] = new int[V + 1]; for(int i = 0; i < E; ) { int j; for(j = i; j < E && edges[j][2] == edges[i][2]; j++) aux[edges[j][1]] = 0; for(j = i; j < E && edges[j][2] == edges[i][2]; j++) aux[edges[j][1]] = Math.max(aux[edges[j][1]], DP[edges[j][0]] + 1); for(j = i; j < E && edges[j][2] == edges[i][2]; j++) DP[edges[j][1]] = Math.max(DP[edges[j][1]] , aux[edges[j][1]]); i = j; } println(Arrays.stream(DP).max().getAsInt()); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
c3c4ffd4ff48e5f7d404b3caf4a80b22
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
; import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int n=sc.nextInt(),m=sc.nextInt(); ArrayList<Point> w[]=new ArrayList[100001]; for (int i=0;i<100001;i++)w[i]=new ArrayList<>(); for (int i=0;i<m;i++){ int a=sc.nextInt(),b=sc.nextInt(); w[sc.nextInt()].add(new Point(a,b)); } int dp[]=new int[n+1]; int tmp[]=new int[n+1]; int ans=0; for (int i=1;i<100001;i++){ for (Point x:w[i]){ tmp[x.y]=0;tmp[x.x]=0; } for (Point x:w[i]){ tmp[x.y]=Math.max(tmp[x.y],dp[x.x]+1); } for (Point x:w[i]){ dp[x.y]=Math.max(tmp[x.y],dp[x.y]); ans=Math.max(ans,dp[x.y]); } } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
75461c1f90f9639d3829a4c7d36ec352
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
// IS BAAR AC HO MADARCHOD import java.io.*; import java.util.*; import static java.lang.Math.*; public class pashmakAndGraph { static ArrayList<pair> adj[]; static void MainSolution() { adj=new ArrayList[300005]; for(int i=0;i<300005;i++)adj[i]=new ArrayList<>(); n=ni();m=ni(); for(int i=0;i<m;i++){ int x=ni(),y=ni(),z=ni(); adj[z].add(new pair(x,y)); } long res[]=new long[n+5],dp[]=new long[n+5]; for(int i=0;i<300005;i++){ for(pair x:adj[i])res[x.b]=0; for(pair x:adj[i])res[x.b]=max(res[x.b],dp[x.a]+1); for(pair x:adj[i])dp[x.b]=max(dp[x.b],res[x.b]); } long max=0; for(long x:dp)max=max(max,x); pl(max); } static class pair{ int a,b; pair(int a, int b){ this.a=a; this.b=b; } } /*-------------------------------------------------------------------------------------------------------------------*/ //THE DON'T CARE ZONE BEGINS HERE...\\ static int mod9 = 1_000_000_007; static int n, m, l, k, t; static AwesomeInput input = new AwesomeInput(System.in); static PrintWriter pw = new PrintWriter(System.out, true); // The Awesome Input Code is a fast IO method // static class AwesomeInput { private InputStream letsDoIT; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private AwesomeInput(InputStream incoming) { this.letsDoIT = incoming; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = letsDoIT.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private long ForLong() { 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 String ForString() { 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 interface SpaceCharFilter { boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return (int) input.ForLong(); } static String ns() { return input.ForString(); } static long nl() { return input.ForLong(); } static double nd() throws IOException { return Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } // Fast Sort is Radix Sort public static int[] fastSort(int[] f) { int n = f.length; int[] to = new int[n]; { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "Vengeance", 1 << 25) //the last parameter is stack size desired. { public void run() { try { double s = System.currentTimeMillis(); MainSolution(); //pl(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s"); pw.flush(); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
d2217054105ffc2e46752e1dd31a43f2
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Map; import java.util.StringTokenizer; /* public class _459E { } */ public class _459E { class edge { int u; int v; int w; /** * @param u * @param v * @param w */ public edge(int u, int v, int w) { super(); this.u = u; this.v = v; this.w = w; } } public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); int m = in.readInteger(); edge[] edges = new edge[m]; for (int i = 0; i < m; i++) { edges[i] = new edge(in.readInteger(), in.readInteger(), in.readInteger()); } Arrays.sort(edges, (e1, e2) -> e1.w - e2.w); int[] maxd = new int[n + 1]; int[] temp = new int[n + 1]; for (int i = 0; i < m;) { int j = i + 1; for (; j < m; j++) { if (edges[j].w > edges[i].w) { break; } } for (int k = i; k < j; k++) { edge ce = edges[k]; temp[ce.v] = Math.max(temp[ce.v], Math.max(maxd[ce.v], maxd[ce.u] + 1)); } for (int k = i; k < j; k++) { edge ce = edges[k]; maxd[ce.v] = temp[ce.v]; } for (int k = i; k < j; k++) { edge ce = edges[k]; temp[ce.v] = 0; } i = j; } int ans = 0; for (int i = 0; i <= n; i++) { ans = Math.max(ans, maxd[i]); } System.out.println(ans); // end here } public static void main(String[] args) throws FileNotFoundException { (new _459E()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
e0ebcc0f17b2ebc71e7be33933bf1823
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<Edge> adj[] = new ArrayList[100001]; for(int i = 0; i <= 100000; ++i) adj[i] = new ArrayList<>(); for(int i = 0; i < m; ++i) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int weight = sc.nextInt(); adj[weight].add(new Edge(u, v)); } int length[] = new int[n]; int curLength[] = new int[n]; for(int i = 1; i <= 100000; ++i) { HashSet<Integer> updList = new HashSet<>(); for(Edge cur : adj[i]) { curLength[cur.v] = max(curLength[cur.v], length[cur.u] + 1); updList.add(cur.v); } for(int j : updList) length[j] = max(length[j], curLength[j]); } int ans = 0; for(int i = 0; i < n; ++i) ans = max(ans, length[i]); w.print(ans); w.close(); } } class Edge { int u, v; Edge(int a, int b) { u = a; v = b; } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
8859c1711eb1f40bdecdf68361723d87
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class E { static int n,m,dp[],que[],dp2[]; static int M = 500000; public static void main(String[] args) throws IOException { /* * 容易超时 */ //Scanner cin = new Scanner(System.in); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); n = Integer.parseInt(tokenizer.nextToken());; m = Integer.parseInt(tokenizer.nextToken());; Edge e[] = new Edge[m]; dp = new int[M]; dp2 = new int[M]; que = new int[M]; for(int i=0;i<m;i++){ e[i] = new Edge(); } for(int i=0;i<m;i++){ tokenizer = new StringTokenizer(reader.readLine()); e[i].from = Integer.parseInt(tokenizer.nextToken()); e[i].to = Integer.parseInt(tokenizer.nextToken()); e[i].v = Integer.parseInt(tokenizer.nextToken()); //System.out.println(e[i].from); } Arrays.sort(e); int max = 0 , top = 0,end = 0;; int pre = -1; for (int i = 0; i < m; i++) { if (pre != e[i].v) { while (top < end) { int x = que[top++]; dp[x] = dp2[x]; } } que[end++] = e[i].to; dp2[e[i].to] = Math.max(dp2[e[i].to], dp[e[i].to]); dp2[e[i].to] = Math.max(dp2[e[i].to], dp[e[i].from] + 1); pre = e[i].v; } while (top < end) { int x = que[top++]; dp[x] = dp2[x]; } for(int i=1;i<=n;i++){ max = Math.max(max,dp[i]); } System.out.println(max); } } class Edge implements Comparable<Edge>{ int to,v,from; public int compareTo(Edge o) { return v - o.v; } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
529c83a92b69e1f3026a1a1331d3875a
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ //hm.get((long)0) != hm.get(0) public class cf5 implements Runnable{ static class pair { int i, j; pair(int i, int j) { this.i = i; this.j = j; } } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(), m = s.nextInt(); ArrayList<pair>[] edge = new ArrayList[(int)1e5 + 1]; for(int i = 1; i <= (int)1e5; i++) edge[i] = new ArrayList<pair>(); for(int i = 0; i < m; i++) { int u = s.nextInt(), v = s.nextInt(), wt = s.nextInt(); edge[wt].add(new pair(u, v)); } int[] dp = new int[n + 1]; for(int i = 1; i <= (int)1e5; i++) { HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int j = 0; j < edge[i].size(); j++) { int u = edge[i].get(j).i, v = edge[i].get(j).j; if(dp[u] + 1 > dp[v] && (hm.get(v) == null || dp[u] + 1 > hm.get(v))) hm.put(v, dp[u] + 1); } for(Map.Entry<Integer, Integer> e : hm.entrySet()) dp[e.getKey()] = e.getValue(); } int res = 0; for(int i = 1; i <= n; i++) res = Math.max(dp[i], res); w.println(res); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new cf5(),"cf5",1<<26).start(); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
4fc6596b24b45d845b284af1731eb590
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; public class CF_459E { public static void main(String[] args) throws IOException { new CF_459E().solve(); } class vertex{ int[] curr={0,0}, prev={0,0}; void updateDest(int w, int l){ if (curr[1]<l){ if(w>curr[0]) prev=curr; curr=new int[]{w, l}; } } int maxPrevLen(int w){ int max=-1; if (curr[0]<w) max=Math.max(max, curr[1]); if (prev[0]<w) max=Math.max(max, prev[1]); if (max==-1) throw new RuntimeException(); return max; } @Override public String toString(){ return Arrays.toString(curr)+" "+Arrays.toString(prev); } } private void solve() throws IOException{ InputStream in = System.in; PrintStream out = System.out; int badTime=2000; // in = new FileInputStream("in.txt"); // out = new PrintStream("out.txt"); // Scanner sc=new Scanner(in); BufferedReader bf=new BufferedReader(new InputStreamReader(in), 32768); StringTokenizer st; st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()), m=Integer.parseInt(st.nextToken()); PriorityQueue<int[]> q=new PriorityQueue<>(100, new Comparator<int[]>(){ @Override public int compare(int[] a, int[] b){ return ((Integer)a[2]).compareTo(b[2]); } }); long start=new Date().getTime(); vertex[] gr=new vertex[n]; for (int i=0;i<n;i++) gr[i]=new vertex(); // System.out.println(Arrays.toString(gr)); for (int i=0;i<m;i++){ st=new StringTokenizer(bf.readLine()); int u=Integer.parseInt(st.nextToken())-1, v=Integer.parseInt(st.nextToken())-1, w=Integer.parseInt(st.nextToken()); if ((new Date().getTime()-start)>badTime) throw new RuntimeException("reading "+i+" from "+m); q.add(new int[]{u, v, w}); } if ((new Date().getTime()-start)>badTime) throw new RuntimeException(); while (!q.isEmpty()){ int[] e=q.poll(); // System.out.println(e[2]); if ((new Date().getTime()-start)>badTime) throw new RuntimeException(""+q.size()); int l=gr[e[0]].maxPrevLen(e[2]); gr[e[1]].updateDest(e[2], l+1); } if ((new Date().getTime()-start)>badTime) throw new RuntimeException(); int maxPath=0, inf=1000_000; for (vertex v: gr) maxPath=Math.max(maxPath, v.maxPrevLen(inf)); out.println(maxPath); } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
7f358f233c1cc0590314dcd236664bcf
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.*; import java.util.*; public class E implements Runnable{ public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(), m = fs.nextInt(); int[][] edges = new int[m][3]; for(int i = 0; i < m; i++) { edges[i][0] = fs.nextInt() - 1; edges[i][1] = fs.nextInt() - 1; edges[i][2] = fs.nextInt(); } Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2])); int[] best = new int[n]; int[] vs = new int[m]; for(int i = 0; i < m; i++) { int j = i; while(j < m && edges[j][2] == edges[i][2]) j++; int ptr = 0; for(int k = i; k < j; k++) { int u = edges[k][0], v = edges[k][1]; vs[ptr++] = Math.max(best[v], 1 + best[u]); } ptr = 0; for(int k = i; k < j; k++) { int u = edges[k][0], v = edges[k][1]; best[v] = Math.max(best[v], vs[ptr++]); } i = j - 1; } int res = 0; for(int i = 0; i < n; i++) res = Math.max(res, best[i]); out.println(res); out.close(); } void sort (int[] a) { int n = a.length; for(int i = 0; i < 50; i++) { Random r = new Random(); int x = r.nextInt(n), y = r.nextInt(n); int temp = a[x]; a[x] = a[y]; a[y] = temp; } Arrays.sort(a); } class FastScanner { 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 FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(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() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } 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; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
ad1910eb55bd68652dc9767b483c21a6
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; public class Round261E { public static void solve() { int n = s.nextInt(); int m = s.nextInt(); int[] max = new int[n]; PriorityQueue<Edge> pq = new PriorityQueue<>(); for(int i = 0; i < m; i++) { int u = s.nextInt() - 1; int v = s.nextInt() - 1; int wt = s.nextInt(); pq.add(new Edge(u, v, wt)); } while(!pq.isEmpty()) { Edge top = pq.poll(); LinkedList<Edge> edges = new LinkedList<>(); edges.add(top); while(!pq.isEmpty() && pq.peek().wt == top.wt) { edges.add(pq.poll()); } int[] changes = new int[edges.size()]; int ptr = 0; for(Edge x : edges) { changes[ptr++] = max[x.v] + 1; } ptr = 0; for(Edge x : edges) { max[x.u] = Integer.max(max[x.u], changes[ptr++]); } } int ans = 0; for(int i = 0; i < n; i++) { ans = Integer.max(ans, max[i]); } out.println(ans); } public static class Edge implements Comparable<Edge> { int u; int v; int wt; public Edge(int u, int v, int wt) { this.u = u; this.v = v; this.wt = wt; } public int compareTo(Edge o) { return o.wt - this.wt; } } public static void main(String[] args) { new Thread(null, null, "Thread", 1 << 27) { public void run() { try { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(System.in); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } public static PrintWriter out; public static FastReader s; public static class FastReader { private InputStream stream; private byte[] buf = new byte[4096]; private int curChar, snumChars; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException E) { throw new InputMismatchException(); } } if (snumChars <= 0) { return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int number = 0; do { number *= 10; number += c - '0'; c = read(); } while (!isSpaceChar(c)); return number * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long number = 0; do { number *= 10L; number += (long) (c - '0'); c = read(); } while (!isSpaceChar(c)); return number * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndofLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndofLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
75ca9991755bf6a663c6f7be8d4a1785
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.awt.geom.Rectangle2D; import java.io.*; import java.math.BigInteger; import java.util.*; import sun.security.krb5.internal.crypto.dk.ArcFourCrypto; public class E { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new E(filePath); } public E(String inputFile) { openInput(inputFile); StringBuilder sb = new StringBuilder(); readNextLine(); int N= NextInt(); int M= NextInt(); Edge [] edges = new Edge[M]; for(int m=0; m<M; m++) { readNextLine(); int u=NextInt()-1; int v=NextInt()-1; int w=NextInt(); edges[m] = new Edge(u, v, w); } Arrays.sort(edges); int [] max = new int[N]; int ret=0; int lastEcost = -1; TreeMap <Integer, Integer> process = new TreeMap<Integer, Integer>(); for(Edge e:edges) { if(e.cost!=lastEcost) { lastEcost = e.cost; for(int x:process.keySet()) { max[x]=Math.max(max[x], process.get(x)); ret = Math.max(ret, max[x]); } process.clear(); } if(max[e.to]<max[e.from]+1) { //max[e.to] = max[e.from]+1; if(process.containsKey(e.to)) { process.put(e.to, Math.max(max[e.from]+1, process.get(e.to))); } else process.put(e.to, max[e.from]+1); } } for(int x:process.keySet()) { max[x]=Math.max(max[x], process.get(x)); ret = Math.max(ret, max[x]); } System.out.println(ret); closeInput(); } private class Edge implements Comparable<Edge> { int from, to, cost; Edge (int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } public int compareTo(Edge d) { return cost - d.cost; } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
2870a20a8de506a89912eba713d70d45
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (PloadyFree@gmail.com) */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); List<Edge>[] edges = new List[(int) 1e5 + 1]; for (int i = 0; i < edges.length; i++) { edges[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = in.readInt() - 1; int v = in.readInt() - 1; int c = in.readInt(); edges[c].add(new Edge(u, v, c)); } int[] d = new int[n]; for (int i = 0; i < edges.length; i++) { List<IntIntPair> newDist = new ArrayList<>(); for (Edge e : edges[i]) { newDist.add(IntIntPair.makePair(e.to, d[e.from] + 1)); } for (IntIntPair p : newDist) { d[p.first] = Math.max(d[p.first], p.second); } } int mx = 0; for (int i : d) { if (i > mx) { mx = i; } } out.print(mx); } class Edge { int from; int to; int weight; public Edge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int 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; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output
PASSED
6c5dd35e0bddddec299da8c21713893e
train_002.jsonl
1408116600
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.ArrayList; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EPashmakAndGraph solver = new EPashmakAndGraph(); solver.solve(1, in, out); out.close(); } static class EPashmakAndGraph { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] edges = new int[m][3]; for (int[] edge : edges) { edge[0] = in.scanInt(); edge[1] = in.scanInt(); edge[2] = in.scanInt(); } Arrays.sort(edges, (o1, o2) -> { return o1[2] - o2[2]; }); int[] dp = new int[n + 1]; int ans = 0; for (int i = 0; i < m; ) { int j = i; List<Integer> values = new ArrayList<>(); while (j < m && edges[j][2] == edges[i][2]) values.add(dp[edges[j++][0]]); int temp = i; while (i < j) { dp[edges[i][1]] = Math.max(values.get(i - temp) + 1, dp[edges[i][1]]); i++; } } for (int i : dp) ans = Math.max(ans, i); out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3 3\n1 2 1\n2 3 1\n3 1 1", "3 3\n1 2 1\n2 3 2\n3 1 3", "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4"]
1 second
["1", "3", "6"]
NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Java 8
standard input
[ "dp", "sortings" ]
bac276604d67fa573b61075c1024865a
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges.
1,900
Print a single integer — the answer to the problem.
standard output